answer
stringlengths
17
10.2M
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.FileSystemException; import com.sleepycat.db.Database; import com.sleepycat.db.DatabaseType; public class DatabaseApp { private String tmpDir; DatabaseType mode; public static void main(String[] args) { DatabaseApp app = new DatabaseApp(); try { app.setup(args); app.run(); } catch (FileSystemException e) { System.err.println(e.getMessage()); } finally { app.cleanup(); } } public void setup(String[] args) throws FileSystemException { if (System.getProperty("os.name").startsWith("Windows")) { tmpDir = "C:\\tmp\\sajust_dir"; } else { tmpDir = "/tmp/sajust_dir"; } /** Select the appropriate mode based on commandline arguments */ try{ if (args[0].equals("btree")) this.mode = DatabaseType.BTREE; if (args[0].equals("hash")) this.mode = DatabaseType.HASH; if (args[0].equals("indexfile")) this.mode = DatabaseType.UNKNOWN; } catch(ArrayIndexOutOfBoundsException e) { System.err.println("Please enter in a commandline argument."); System.err.println("Acceptable options are: btree, hash, indexfile"); System.exit(1); } File tDirFile = new File(tmpDir); if (tDirFile.exists()) tDirFile.delete(); if (!(new File(tmpDir)).mkdirs()) { throw new FileSystemException("Failed to create temp folder"); } } Database indexdb = null; public void run() { Database db = DbHelper.create(tmpDir + File.separator + "table.db", mode); /** Display the main menu, prompt the user for which db type is being used * */ while (true) { System.out.println("CMPUT 291 Project 2"); System.out.println(" System.out.println("Select Option"); System.out.println("1) Create and populate the database"); System.out.println("2) Retrieve records with a given key"); System.out.println("3) Retrieve records with a given data"); System.out.println("4) Retrieve records with a given range of key values"); System.out.println("5) Destroy the database"); System.out.println("6) Quit"); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(System.in)); Integer inputnumber = 0; try { String input = br.readLine(); inputnumber = Integer.parseInt(input); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NumberFormatException e) { System.out.println("Invalid Entry, please try again"); continue; } switch(inputnumber) { case 1: if (this.mode == DatabaseType.BTREE || this.mode == DatabaseType.HASH){ DbHelper.populateTable(db, 100000); } else if (this.mode == DatabaseType.UNKNOWN) { DbHelper.populateTable(db, 100000); DbHelper.populateIndexFile(db); //now we have to make a b-tree database out of the indexfile for reverse lookup this.indexdb = DbHelper.create(tmpDir + File.separator + "table.db", DatabaseType.BTREE); DbHelper.PopulateDBbyFile(indexdb, "indexfile"); } break; case 2: System.out.println("Enter Search Key"); String searchkey; searchkey = inputKey(); DbHelper.getByKey(db, searchkey); break; case 3: if (this.mode == DatabaseType.BTREE || this.mode == DatabaseType.HASH){ System.out.println("Enter search value"); DbHelper.getByValueNoIndex(db, inputKey()); } else { DbHelper.getByKey(indexdb, inputKey()); } break; case 4: System.out.print("Start of range?: "); String startKey = inputKey(); System.out.print("End of range?: "); String endKey = inputKey(); DbHelper.retrieveRange(db, startKey, endKey); break; case 5: File dbFile = new File(tmpDir + File.separator + "table.db"); if (dbFile.exists()) dbFile.delete(); System.out.println("Deleted database file"); break; case 6: System.exit(0); break; } } } public void cleanup() { File tDirFile = new File(tmpDir); File dbFile = new File(tmpDir + File.separator + "table.db"); if (dbFile.exists() || tDirFile.exists()){ dbFile.delete(); tDirFile.delete(); } } /** * Prompt for key * @return Key string */ private String inputKey() { BufferedReader br = null; br = new BufferedReader(new InputStreamReader(System.in)); String key; while(true) { try { key = br.readLine(); // Return value from input // if (key.length() < 64) { // System.err.println("Key must be at least 64 characters long"); // continue; if (key.length() > 127) { System.err.println("Key must be shorter than 128 characters"); continue; } return key; } catch (IOException e) { System.err.println("Error retrieving value"); } } } }
package wge3.entity.character; import java.util.*; import wge3.entity.terrainelement.Item; public class Inventory { private Map<Item, Integer> items; public Inventory() { items = new HashMap<Item, Integer>(); } public Set<Item> getItems() { return items.keySet(); } public void addItem(Item item) { addItem(item, 1); } public void addItem(Item item, int amount) { if (!items.containsKey(item)) { items.put(item, amount); } else { items.replace(item, items.get(item) + amount); } } public void removeItem(Item item) { removeItem(item, 1); } public void removeItem(Item item, int amount) { if (items.get(item) - amount <= 0) { items.remove(item); } else { items.replace(item, items.get(item) - amount); } } public int getAmount(Item item) { return items.get(item); } public Item getItem(int index) { return null; } }
package com.mypurecloud.sdk.v2; import com.mypurecloud.sdk.v2.connector.ApiClientConnectorResponse; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.base.Stopwatch; import java.util.concurrent.TimeUnit; import java.util.List; import java.util.Map; import java.util.HashMap; import java.io.InputStream; import java.io.IOException; public class ApiClientRetryTest { @Test(priority = 1) public void shouldRetryTestWith_200() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 200; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Retry-After", "1"); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); retryConfiguration.setMaxRetryTime(30); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); Stopwatch stopwatch = Stopwatch.createStarted(); boolean result = retry.shouldRetry(response); Assert.assertEquals(false, result, "Status Code is 200, so shouldRetry method returns false"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 100); stopwatch.stop(); } @Test(priority = 2) public void shouldRetryTestWith_429() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 429; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Retry-After", "1"); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); retryConfiguration.setMaxRetryTime(30); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); Stopwatch stopwatch = Stopwatch.createStarted(); boolean result = retry.shouldRetry(response); Assert.assertEquals(true, result, "Status Code is 429, so it will sleep for 1 Sec as provided in Retry-After header and returns true"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 1100); stopwatch.stop(); } @Test(priority = 3) public void shouldRetryTestWith_502() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 502; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Retry-After", "1"); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); retryConfiguration.setMaxRetryTime(30); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); Stopwatch stopwatch = Stopwatch.createStarted(); boolean result = retry.shouldRetry(response); Assert.assertEquals(true, result, "Status Code is 502, so it will sleep for 1 Sec as provided in Retry-After header and returns true"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 1100); stopwatch.stop(); } @Test(priority = 4) public void shouldRetryTestWith_502_And_0_MaxRetryTime() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 502; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Retry-After", "3"); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); Stopwatch stopwatch = Stopwatch.createStarted(); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); boolean result = retry.shouldRetry(response); Assert.assertEquals(false, result, "Even though Status Code is 502, it will return false because MaxRetryTime is set to Zero by default"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 100); stopwatch.stop(); } @Test(priority = 5) public void shouldRetryTestWith_503_And_RetryConfig() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 503; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); headers.put("Retry-After", "3"); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); retryConfiguration.setBackoffInterval(6000L); retryConfiguration.setDefaultDelay(1); retryConfiguration.setMaxRetryTime(10); retryConfiguration.setMaxRetriesBeforeBackoff(0); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); Stopwatch stopwatch = Stopwatch.createStarted(); boolean result = retry.shouldRetry(response); Assert.assertEquals(true, result, "Since Status Code is 503 and maxRetriesBeforeBackoff is Zero, backoff block will be executed and returns true"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 3100); stopwatch.stop(); } @Test(priority = 6) public void shouldRetryTestWith_504_And_No_RetryAfter_Header() throws IOException { ApiClientConnectorResponse response = new ApiClientConnectorResponse() { @Override public int getStatusCode() { return 504; } @Override public String getStatusReasonPhrase() { return null; } @Override public Map<String, String> getHeaders() { Map<String, String> headers = new HashMap<>(); return headers; } @Override public boolean hasBody() { return false; } @Override public String readBody() throws IOException { return null; } @Override public InputStream getBody() throws IOException { return null; } @Override public void close() throws Exception { } }; ApiClient.RetryConfiguration retryConfiguration = new ApiClient.RetryConfiguration(); retryConfiguration.setMaxRetryTime(30); ApiClient.Retry retry = new ApiClient.Retry(retryConfiguration); Stopwatch stopwatch = Stopwatch.createStarted(); boolean result = retry.shouldRetry(response); Assert.assertEquals(true, result, "Even though Retry-After header is missing, it will sleep for 3 Sec by default and returns true"); Assert.assertTrue(stopwatch.elapsed(TimeUnit.MILLISECONDS) < 3100); stopwatch.stop(); } }
package org.pentaho.di.version; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import org.pentaho.di.core.Const; /** * Singleton class to allow us to see on which date & time the kettle3.jar was built. * * @author Matt * @since 2006-aug-12 */ public class BuildVersion { /** name of the Kettle version file, updated in the ant script, contains date and time of build */ public static final String BUILD_VERSION_FILE = "build_version.txt"; public static final String SEPARATOR = "@"; public static final String BUILD_DATE_FORMAT = "yyyy/MM/dd'T'HH:mm:ss"; private static BuildVersion buildVersion; /** * @return the instance of the BuildVersion singleton */ public static final BuildVersion getInstance() { if (buildVersion!=null) return buildVersion; buildVersion = new BuildVersion(); return buildVersion; } private int version; private Date buildDate; private String hostname; private BuildVersion() { String filename = BUILD_VERSION_FILE; StringBuffer buffer = new StringBuffer(30); try { // The version file only contains a single lines of text InputStream inputStream = getClass().getResourceAsStream( "/"+filename ); // try to find it in the jars... if (inputStream==null) // not found { // System.out.println("Stream not found for filename [/"+filename+"], looking for it on the normal filesystem..."); try { inputStream = new FileInputStream(filename); // Retry from normal file system } catch(FileNotFoundException e) { inputStream = new FileInputStream("./"+filename); } } else { } // read the file into a String int c=inputStream.read(); while ( c>0 && c!='\n' && c!='\r' ) { if (c!=' ' && c!='\t') buffer.append((char)c); // no spaces or tabs please ;-) c=inputStream.read(); } // The 3 parts we expect are in here: String parts[] = buffer.toString().split(SEPARATOR); if (parts.length!=3) { throw new RuntimeException("Could not find 3 parts in versioning line : ["+buffer+"]"); } // Get the revision version = Integer.parseInt(parts[0]); // Get the build date SimpleDateFormat format = new SimpleDateFormat(BUILD_DATE_FORMAT); buildDate = format.parse(parts[1]); try { File engineJar = new File("lib/kettle-engine.jar"); long lastModifiedJar = engineJar.lastModified(); if (lastModifiedJar!=0L) { buildDate = new Date(lastModifiedJar); } else { System.out.println("Unable to find kettle engine jar file to set build date. (ingored)"); } } catch(Exception e) { // Eat this exception, keep things the way the were before. // Eats security exceptions, etc. } } catch(Exception e) { System.out.println("Unable to load revision number from file : ["+filename+"] : "+e.toString()); System.out.println(Const.getStackTracker(e)); version = 1; buildDate = new Date(); } } /** * @return the buildDate */ public Date getBuildDate() { return buildDate; } /** * @param buildDate the buildDate to set */ public void setBuildDate(Date buildDate) { this.buildDate = buildDate; } /** * @return the revision */ public int getVersion() { return version; } /** * @param revision the revision to set */ public void setVersion(int revision) { this.version = revision; } public void save() { FileWriter fileWriter = null; String filename = BUILD_VERSION_FILE; File file = new File( filename ); try { fileWriter = new FileWriter(file); // First write the revision fileWriter.write(Integer.toString(version)+" "); // Then the separator fileWriter.write(SEPARATOR); // Finally the build date SimpleDateFormat format = new SimpleDateFormat(BUILD_DATE_FORMAT); fileWriter.write(" "+format.format(buildDate)+" "); // Then the separator fileWriter.write(SEPARATOR); // Then the hostname fileWriter.write(" "+Const.getHostname()); // Return fileWriter.write(Const.CR); System.out.println("Saved build version info to file ["+file.getAbsolutePath()+"]"); } catch(Exception e) { throw new RuntimeException("Unable to save revision information to file ["+BUILD_VERSION_FILE+"]", e); } finally { try { if (fileWriter!=null) { fileWriter.close(); } } catch(Exception e) { throw new RuntimeException("Unable to close file ["+BUILD_VERSION_FILE+"] after writing", e); } } } /** * @return the hostname */ public String getHostname() { return hostname; } /** * @param hostname the hostname to set */ public void setHostname(String hostname) { this.hostname = hostname; } }
package uk.org.ponder.rsf.template; import java.util.HashMap; import uk.org.ponder.arrayutil.ArrayUtil; /** * A primitive "lump" of an XML document, representing a "significant" * character span. The basic function is to hold indexes start, length into * the character array for the document, as well as various housekeeping * information to aid navigation and debugging. * * @author Antranig Basman (antranig@caret.cam.ac.uk) */ public class XMLLump { /** This string is used as separator between transition entries in forwardmap, * of the form "old-id-suffix new-id-suffix" */ public static final String TRANSITION_SEPARATOR = " "; public int lumpindex; public int line, column; public int nestingdepth; public XMLViewTemplate parent; public int start, length; public String rsfID; public XMLLump open_end = null; // lump containing " >" public XMLLump close_tag = null; // lump containing "</close"> public XMLLump uplump = null; // open and close will be the same for empty tag case " />" // headlump has standard text of |<tagname | to allow easy identification. public XMLLumpMMap downmap = null; // map from attribute name to lump where value occurs. // this may be reformed to map to text if we collapse attribute lumps? public HashMap attributemap = null; // the (XHTML) attribute appearing in the template file designating a // template component. public static final String ID_ATTRIBUTE = "rsf:id"; // A value for the rsf:id attribute representing a component that needs // URL rewriting (issued URLs beginning with root /). NEVER issue a component // with this ID! public static final String SCR_PREFIX = "scr="; // Value for rsf:id that represents a CollectingSCR public static final String SCR_CONTRIBUTE_PREFIX = "scr=contribute-"; public static final String URL_REWRITE = "rewrite-url"; // A value for the rsf:id attribute indicating that the actual (leaf) component // to be targetted by component rendering is somewhere inside the component // holding the ID. NEVER issue a component with this ID! In this case, the // component holding the ID will be either a div or a span. public static final String PAYLOAD_COMPONENT = "payload-component"; // this occurs in the SAME CONTAINER scope as the target??? public static final String FORID_PREFIX = "message-for";// + SplitID.SEPARATOR; public static final String FORID_SUFFIX = ":*"; public XMLLump() {} public XMLLump(int lumpindex, int nestingdepth) { this.lumpindex = lumpindex; this.nestingdepth = nestingdepth; } public boolean textEquals(String tocheck) { return ArrayUtil.equals(tocheck, parent.buffer, start, length); } public static String tagToText(String tagname) { return "<" + tagname + " "; } public static String textToTag(String text) { return text.substring(1, text.length() - 1); } public String getTag() { return new String(parent.buffer, start + 1, length - 2); } public String toDebugString() { return "lump index " + lumpindex + " line " + line + " column " + column; } public String toString() { return new String(parent.buffer, start, length) + " at " + toDebugString() + (parent.fullpath == null? "" : " in file " + parent.fullpath); } }
package com.rultor.web; import com.rexsl.page.auth.Identity; import javax.validation.ConstraintViolationException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Test; /** * Test case for {@link AuthKeys}. * @author Shailendra Soni (soni_shailendra02@yahoo.com) * @version $Id$ */ public class AuthKeysTest { /** * Validate weather user is null or not. * @throws Exception If test fails */ @Test(expected = ConstraintViolationException.class) public final void validateNullUser() throws Exception { final AuthKeys authKeys = new AuthKeys(); authKeys.authenticate(null, "password"); } /** * It should be throw exception if password is given null. * @throws Exception If test fails */ @Test(expected = ConstraintViolationException.class) public final void validateNullPassword() throws Exception { final AuthKeys authKeys = new AuthKeys(); authKeys.authenticate("urn:git:soni", null); } /** * AuthKeys should authenticate URN. * @throws Exception If test fails */ @Test public final void authenticateURN() throws Exception { final AuthKeys authKeys = new AuthKeys(); MatcherAssert.assertThat( authKeys.authenticate("urn:git:rultor", "test").name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); } /** * Execute method with Empty String. * @throws Exception If test fails * @todo #238 AuthKeys should validate empty string. */ @Ignore @Test(expected = IllegalArgumentException.class) public final void authenticateURNWithEmptyUser() throws Exception { final AuthKeys authKeys = new AuthKeys(); MatcherAssert.assertThat( authKeys.authenticate("", "").name(), Matchers.equalTo(Identity.ANONYMOUS.name()) ); } }
package net.runelite.api; import lombok.Getter; /** * A hitsplat that has been applied to an {@link Actor}. */ public class Hitsplat { /** * An enumeration of hitsplat types. */ public enum HitsplatType { /** * Blocking damage by me (blue). */ BLOCK_ME, /** * Blocking damage by others (blue). */ BLOCK_OTHER, /** * Taking damage by me (red). */ DAMAGE_ME, /** * Taking damage by others (red). */ DAMAGE_OTHER, /** * Taking damage by me (cyan). */ DAMAGE_ME_CYAN, /** * Taking damage by others (cyan). */ DAMAGE_OTHER_CYAN, /** * Taking damage by me (orange). */ DAMAGE_ME_ORANGE, /** * Taking damage by others (orange). */ DAMAGE_OTHER_ORANGE, /** * Taking damage by me (yellow). */ DAMAGE_ME_YELLOW, /** * Taking damage by others (yellow). */ DAMAGE_OTHER_YELLOW, /** * Taking damage by me (white). */ DAMAGE_ME_WHITE, /** * Taking damage by others (white/black). */ DAMAGE_OTHER_WHITE, /** * Damage from poison (green). */ POISON, /** * Damage from venom (teal). */ VENOM, /** * Damage from disease (orange). */ DISEASE, /** * Healing (purple). */ HEAL, DAMAGE_MAX_ME, DAMAGE_MAX_ME_CYAN, DAMAGE_MAX_ME_ORANGE, DAMAGE_MAX_ME_YELLOW, DAMAGE_MAX_ME_WHITE; /** * Utility method that maps the type value to its respective * {@link Hitsplat} value. * * @param type the type value * @return hitsplat type */ public static HitsplatType fromInteger(int type) { switch (type) { case 12: return BLOCK_ME; case 13: return BLOCK_OTHER; case 16: return DAMAGE_ME; case 17: return DAMAGE_OTHER; case 2: return POISON; case 4: return DISEASE; case 5: return VENOM; case 6: return HEAL; case 18: return DAMAGE_ME_CYAN; case 19: return DAMAGE_OTHER_CYAN; case 20: return DAMAGE_ME_ORANGE; case 21: return DAMAGE_OTHER_ORANGE; case 22: return DAMAGE_ME_YELLOW; case 23: return DAMAGE_OTHER_YELLOW; case 24: return DAMAGE_ME_WHITE; case 25: return DAMAGE_OTHER_WHITE; case 43: return DAMAGE_MAX_ME; case 44: return DAMAGE_MAX_ME_CYAN; case 45: return DAMAGE_MAX_ME_ORANGE; case 46: return DAMAGE_MAX_ME_YELLOW; case 47: return DAMAGE_MAX_ME_WHITE; } return null; } } /** * The type of hitsplat. */ @Getter private HitsplatType hitsplatType; /** * The value displayed by the hitsplat. */ @Getter private int amount; /** * When the hitsplat will disappear. */ @Getter private int disappearsOnGameCycle; public Hitsplat(HitsplatType hitsplatType, int amount, int disappearsOnGameCycle) { this.hitsplatType = hitsplatType; this.amount = amount; this.disappearsOnGameCycle = disappearsOnGameCycle; } public boolean isMine() { switch (this.getHitsplatType()) { case BLOCK_ME: case DAMAGE_ME: case DAMAGE_ME_CYAN: case DAMAGE_ME_YELLOW: case DAMAGE_ME_ORANGE: case DAMAGE_ME_WHITE: case DAMAGE_MAX_ME: case DAMAGE_MAX_ME_CYAN: case DAMAGE_MAX_ME_ORANGE: case DAMAGE_MAX_ME_YELLOW: case DAMAGE_MAX_ME_WHITE: return true; default: return false; } } public boolean isOthers() { switch (this.getHitsplatType()) { case BLOCK_OTHER: case DAMAGE_OTHER: case DAMAGE_OTHER_CYAN: case DAMAGE_OTHER_YELLOW: case DAMAGE_OTHER_ORANGE: case DAMAGE_OTHER_WHITE: return true; default: return false; } } }
package org.openecard.sal; import iso.std.iso_iec._24727.tech.schema.ACLList; import iso.std.iso_iec._24727.tech.schema.ACLListResponse; import iso.std.iso_iec._24727.tech.schema.ACLModify; import iso.std.iso_iec._24727.tech.schema.ACLModifyResponse; import iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType; import iso.std.iso_iec._24727.tech.schema.AuthorizationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationList; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationPath; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribe; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribeResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoad; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoadResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceType; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationType; import iso.std.iso_iec._24727.tech.schema.Connect; import iso.std.iso_iec._24727.tech.schema.ConnectResponse; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType; import iso.std.iso_iec._24727.tech.schema.ConnectionServiceActionName; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticate; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType; import iso.std.iso_iec._24727.tech.schema.DIDCreate; import iso.std.iso_iec._24727.tech.schema.DIDCreateResponse; import iso.std.iso_iec._24727.tech.schema.DIDDelete; import iso.std.iso_iec._24727.tech.schema.DIDDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DIDGet; import iso.std.iso_iec._24727.tech.schema.DIDGetResponse; import iso.std.iso_iec._24727.tech.schema.DIDInfoType; import iso.std.iso_iec._24727.tech.schema.DIDList; import iso.std.iso_iec._24727.tech.schema.DIDListResponse; import iso.std.iso_iec._24727.tech.schema.DIDNameListType; import iso.std.iso_iec._24727.tech.schema.DIDQualifierType; import iso.std.iso_iec._24727.tech.schema.DIDStructureType; import iso.std.iso_iec._24727.tech.schema.DIDUpdate; import iso.std.iso_iec._24727.tech.schema.DIDUpdateDataType; import iso.std.iso_iec._24727.tech.schema.DIDUpdateResponse; import iso.std.iso_iec._24727.tech.schema.DSICreate; import iso.std.iso_iec._24727.tech.schema.DSICreateResponse; import iso.std.iso_iec._24727.tech.schema.DSIDelete; import iso.std.iso_iec._24727.tech.schema.DSIDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DSIList; import iso.std.iso_iec._24727.tech.schema.DSIListResponse; import iso.std.iso_iec._24727.tech.schema.DSINameListType; import iso.std.iso_iec._24727.tech.schema.DSIRead; import iso.std.iso_iec._24727.tech.schema.DSIReadResponse; import iso.std.iso_iec._24727.tech.schema.DSIWrite; import iso.std.iso_iec._24727.tech.schema.DSIWriteResponse; import iso.std.iso_iec._24727.tech.schema.DSIType; import iso.std.iso_iec._24727.tech.schema.DataSetCreate; import iso.std.iso_iec._24727.tech.schema.DataSetCreateResponse; import iso.std.iso_iec._24727.tech.schema.DataSetDelete; import iso.std.iso_iec._24727.tech.schema.DataSetDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetInfoType; import iso.std.iso_iec._24727.tech.schema.DataSetList; import iso.std.iso_iec._24727.tech.schema.DataSetListResponse; import iso.std.iso_iec._24727.tech.schema.DataSetNameListType; import iso.std.iso_iec._24727.tech.schema.DataSetSelect; import iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse; import iso.std.iso_iec._24727.tech.schema.Decipher; import iso.std.iso_iec._24727.tech.schema.DecipherResponse; import iso.std.iso_iec._24727.tech.schema.DifferentialIdentityServiceActionName; import iso.std.iso_iec._24727.tech.schema.Disconnect; import iso.std.iso_iec._24727.tech.schema.DisconnectResponse; import iso.std.iso_iec._24727.tech.schema.Encipher; import iso.std.iso_iec._24727.tech.schema.EncipherResponse; import iso.std.iso_iec._24727.tech.schema.ExecuteAction; import iso.std.iso_iec._24727.tech.schema.ExecuteActionResponse; import iso.std.iso_iec._24727.tech.schema.GetRandom; import iso.std.iso_iec._24727.tech.schema.GetRandomResponse; import iso.std.iso_iec._24727.tech.schema.Hash; import iso.std.iso_iec._24727.tech.schema.HashResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.InitializeResponse; import iso.std.iso_iec._24727.tech.schema.NamedDataServiceActionName; import iso.std.iso_iec._24727.tech.schema.Sign; import iso.std.iso_iec._24727.tech.schema.SignResponse; import iso.std.iso_iec._24727.tech.schema.TargetNameType; import iso.std.iso_iec._24727.tech.schema.Terminate; import iso.std.iso_iec._24727.tech.schema.TerminateResponse; import iso.std.iso_iec._24727.tech.schema.VerifyCertificate; import iso.std.iso_iec._24727.tech.schema.VerifyCertificateResponse; import iso.std.iso_iec._24727.tech.schema.VerifySignature; import iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse; import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.openecard.addon.AddonManager; import org.openecard.addon.AddonNotFoundException; import org.openecard.addon.AddonSelector; import org.openecard.addon.HighestVersionSelector; import org.openecard.addon.sal.FunctionType; import org.openecard.addon.sal.SALProtocol; import org.openecard.common.ECardConstants; import org.openecard.common.ECardException; import org.openecard.common.WSHelper; import org.openecard.common.apdu.DeleteFile; import org.openecard.common.apdu.EraseBinary; import org.openecard.common.apdu.EraseRecord; import org.openecard.common.apdu.Select; import org.openecard.common.apdu.UpdateBinary; import org.openecard.common.apdu.UpdateRecord; import org.openecard.common.apdu.WriteBinary; import org.openecard.common.apdu.WriteRecord; import org.openecard.common.apdu.common.CardCommandAPDU; import org.openecard.common.apdu.common.CardResponseAPDU; import org.openecard.common.apdu.utils.CardUtils; import org.openecard.common.interfaces.Environment; import org.openecard.common.sal.Assert; import org.openecard.common.sal.anytype.CryptoMarkerType; import org.openecard.common.sal.exception.InappropriateProtocolForActionException; import org.openecard.common.sal.exception.IncorrectParameterException; import org.openecard.common.sal.exception.NameExistsException; import org.openecard.common.sal.exception.NamedEntityNotFoundException; import org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException; import org.openecard.common.sal.exception.UnknownConnectionHandleException; import org.openecard.common.sal.exception.UnknownProtocolException; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.cif.CardApplicationWrapper; import org.openecard.common.sal.state.cif.CardInfoWrapper; import org.openecard.common.sal.util.SALUtils; import org.openecard.common.tlv.iso7816.DataElements; import org.openecard.common.tlv.iso7816.FCP; import org.openecard.gui.UserConsent; import org.openecard.ws.SAL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TinySAL implements SAL { private static final Logger logger = LoggerFactory.getLogger(TinySAL.class); private final Environment env; private final CardStateMap states; private AddonSelector protocolSelector; private UserConsent userConsent; /** * Creates a new TinySAL. * * @param env Environment * @param states CardStateMap */ public TinySAL(Environment env, CardStateMap states) { this.env = env; this.states = states; } public void setAddonManager(AddonManager manager) { protocolSelector = new AddonSelector(manager); protocolSelector.setStrategy(new HighestVersionSelector()); } /** * The Initialize function is executed when the ISO24727-3-Interface is invoked for the first time. * The interface is initialised with this function. * See BSI-TR-03112-4, version 1.1.2, section 3.1.1. * * @param request Initialize * @return InitializeResponse */ @Override public InitializeResponse initialize(Initialize request) { return WSHelper.makeResponse(InitializeResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The Terminate function is executed when the ISO24727-3-Interface is terminated. * This function closes all established connections and open sessions. * See BSI-TR-03112-4, version 1.1.2, section 3.1.2. * * @param request Terminate * @return TerminateResponse */ @Override public TerminateResponse terminate(Terminate request) { return WSHelper.makeResponse(TerminateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationPath function determines a path between the client application and a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.1.3. * * @param request CardApplicationPath * @return CardApplicationPathResponse */ @Override public CardApplicationPathResponse cardApplicationPath(CardApplicationPath request) { CardApplicationPathResponse response = WSHelper.makeResponse(CardApplicationPathResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardAppPathRequest(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> entries = states.getMatchingEntries(cardAppPath); // Copy entries to result set CardAppPathResultSet resultSet = new CardAppPathResultSet(); List<CardApplicationPathType> resultPaths = resultSet.getCardApplicationPathResult(); for (CardStateEntry entry : entries) { CardApplicationPathType pathCopy = entry.pathCopy(); if (cardAppPath.getCardApplication() != null) { pathCopy.setCardApplication(cardAppPath.getCardApplication()); } else { pathCopy.setCardApplication(entry.getImplicitlySelectedApplicationIdentifier()); } resultPaths.add(pathCopy); } response.setCardAppPathResultSet(resultSet); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationConnect function establishes an unauthenticated connection between the client * application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.1. * * @param request CardApplicationConnect * @return CardApplicationConnectResponse */ @Override public CardApplicationConnectResponse cardApplicationConnect(CardApplicationConnect request) { CardApplicationConnectResponse response = WSHelper.makeResponse(CardApplicationConnectResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardApplicationPath(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> cardStateEntrySet = states.getMatchingEntries(cardAppPath, false); Assert.assertIncorrectParameter(cardStateEntrySet, "The given ConnectionHandle is invalid."); /* * [TR-03112-4] If the provided path fragments are valid for more than one card application * the eCard-API-Framework SHALL return any of the possible choices. */ CardStateEntry cardStateEntry = cardStateEntrySet.iterator().next(); byte[] applicationID = cardAppPath.getCardApplication(); if (applicationID == null) { applicationID = cardStateEntry.getImplicitlySelectedApplicationIdentifier(); } Assert.securityConditionApplication(cardStateEntry, applicationID, ConnectionServiceActionName.CARD_APPLICATION_CONNECT); // Connect to the card CardApplicationPathType cardApplicationPath = cardStateEntry.pathCopy(); Connect connect = new Connect(); connect.setContextHandle(cardApplicationPath.getContextHandle()); connect.setIFDName(cardApplicationPath.getIFDName()); connect.setSlot(cardApplicationPath.getSlotIndex()); ConnectResponse connectResponse = (ConnectResponse) env.getDispatcher().deliver(connect); WSHelper.checkResult(connectResponse); // Select the card application CardCommandAPDU select; // TODO: proper determination of path, file and app id if (applicationID.length == 2) { select = new Select.File(applicationID); } else { select = new Select.Application(applicationID); } select.transmit(env.getDispatcher(), connectResponse.getSlotHandle()); cardStateEntry.setCurrentCardApplication(applicationID); cardStateEntry.setSlotHandle(connectResponse.getSlotHandle()); // reset the ef FCP cardStateEntry.unsetFCPOfSelectedEF(); states.addEntry(cardStateEntry); response.setConnectionHandle(cardStateEntry.handleCopy()); response.getConnectionHandle().setCardApplication(applicationID); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationDisconnect function terminates the connection to a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.2. * * @param request CardApplicationDisconnect * @return CardApplicationDisconnectResponse */ @Override public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) { CardApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] slotHandle = connectionHandle.getSlotHandle(); // check existence of required parameters if (slotHandle == null) { return WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "ConnectionHandle is null")); } Disconnect disconnect = new Disconnect(); disconnect.setSlotHandle(slotHandle); DisconnectResponse disconnectResponse = (DisconnectResponse) env.getDispatcher().deliver(disconnect); // remove entries associated with this handle states.removeSlotHandleEntry(slotHandle); response.setResult(disconnectResponse.getResult()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * This CardApplicationStartSession function starts a session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.3. * * @param request CardApplicationStartSession * @return CardApplicationStartSessionResponse */ @Override public CardApplicationStartSessionResponse cardApplicationStartSession(CardApplicationStartSession request) { CardApplicationStartSessionResponse response = WSHelper.makeResponse(CardApplicationStartSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter didName is empty."); DIDAuthenticationDataType didAuthenticationProtocolData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationProtocolData, "The parameter didAuthenticationProtocolData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_START_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationStartSession)) { response = protocol.cardApplicationStartSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationStartSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationEndSession function closes the session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.4. * * @param request CardApplicationEndSession * @return CardApplicationEndSessionResponse */ @Override public CardApplicationEndSessionResponse cardApplicationEndSession(CardApplicationEndSession request) { CardApplicationEndSessionResponse response = WSHelper.makeResponse(CardApplicationEndSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_END_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationEndSession)) { response = protocol.cardApplicationEndSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationEndSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationList function returns a list of the available card applications on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.3.1. * * @param request CardApplicationList * @return CardApplicationListResponse */ @Override public CardApplicationListResponse cardApplicationList(CardApplicationList request) { CardApplicationListResponse response = WSHelper.makeResponse(CardApplicationListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, CardApplicationServiceActionName.CARD_APPLICATION_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); CardApplicationNameList cardApplicationNameList = new CardApplicationNameList(); cardApplicationNameList.getCardApplicationName().addAll(cardInfoWrapper.getCardApplicationNameList()); response.setCardApplicationNameList(cardApplicationNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } @Override public CardApplicationCreateResponse cardApplicationCreate(CardApplicationCreate request) { return WSHelper.makeResponse(CardApplicationCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationDelete function deletes a card application as well as all corresponding * data sets, DSIs, DIDs and services. * See BSI-TR-03112-4, version 1.1.2, section 3.3.3. * * @param request CardApplicationDelete * @return CardApplicationDeleteResponse */ @Override public CardApplicationDeleteResponse cardApplicationDelete(CardApplicationDelete request) { CardApplicationDeleteResponse response = WSHelper.makeResponse(CardApplicationDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationName = request.getCardApplicationName(); Assert.assertIncorrectParameter(cardApplicationName, "The parameter CardApplicationName is empty."); Assert.securityConditionApplication(cardStateEntry, connectionHandle.getCardApplication(), CardApplicationServiceActionName.CARD_APPLICATION_DELETE); DeleteFile delFile = new DeleteFile.Application(connectionHandle.getCardApplication()); delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceList function returns a list of all available services of a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.4. * * @param request CardApplicationServiceList * @return CardApplicationServiceListResponse */ @Override public CardApplicationServiceListResponse cardApplicationServiceList(CardApplicationServiceList request) { CardApplicationServiceListResponse response = WSHelper.makeResponse(CardApplicationServiceListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, // CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_LIST); CardApplicationServiceNameList cardApplicationServiceNameList = new CardApplicationServiceNameList(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)) { Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); cardApplicationServiceNameList.getCardApplicationServiceName().add(nextt.getCardApplicationServiceName()); } } } response.setCardApplicationServiceNameList(cardApplicationServiceNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceCreate function creates a new service in the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.5. * * @param request CardApplicationServiceCreate * @return CardApplicationServiceCreateResponse */ @Override public CardApplicationServiceCreateResponse cardApplicationServiceCreate(CardApplicationServiceCreate request) { return WSHelper.makeResponse(CardApplicationServiceCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Code for a specific card application service was loaded into the card application with the aid * of the CardApplicationServiceLoad function. * See BSI-TR-03112-4, version 1.1.2, section 3.3.6. * * @param request CardApplicationServiceLoad * @return CardApplicationServiceLoadResponse */ @Override public CardApplicationServiceLoadResponse cardApplicationServiceLoad(CardApplicationServiceLoad request) { return WSHelper.makeResponse(CardApplicationServiceLoadResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDelete function deletes a card application service in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.7. * * @param request CardApplicationServiceDelete * @return CardApplicationServiceDeleteResponse */ @Override public CardApplicationServiceDeleteResponse cardApplicationServiceDelete(CardApplicationServiceDelete request) { return WSHelper.makeResponse(CardApplicationServiceDeleteResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDescribe function can be used to request an URI, an URL or a detailed description * of the selected card application service. * See BSI-TR-03112-4, version 1.1.2, section 3.3.8. * * @param request CardApplicationServiceDescribe * @return CardApplicationServiceDescribeResponse */ @Override public CardApplicationServiceDescribeResponse cardApplicationServiceDescribe(CardApplicationServiceDescribe request) { CardApplicationServiceDescribeResponse response = WSHelper.makeResponse(CardApplicationServiceDescribeResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String cardApplicationServiceName = request.getCardApplicationServiceName(); Assert.assertIncorrectParameter(cardApplicationServiceName, "The parameter CardApplicationServiceName is empty."); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, // CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_DESCRIBE); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)){ Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); if (nextt.getCardApplicationServiceName().equals(cardApplicationServiceName)) { response.setServiceDescription(nextt.getCardApplicationServiceDescription()); } } } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ExecuteAction function permits use of additional card application services by the client application * which are not explicitly specified in [ISO24727-3] but which can be implemented by the eCard with additional code. * See BSI-TR-03112-4, version 1.1.2, section 3.3.9. * * @param request ExecuteAction * @return ExecuteActionResponse */ @Override public ExecuteActionResponse executeAction(ExecuteAction request) { return WSHelper.makeResponse(ExecuteActionResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The DataSetList function returns the list of the data sets in the card application addressed with the * ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.4.1. * * @param request DataSetList * @return DataSetListResponse */ @Override public DataSetListResponse dataSetList(DataSetList request) { DataSetListResponse response = WSHelper.makeResponse(DataSetListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, NamedDataServiceActionName.DATA_SET_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetNameListType dataSetNameList = cardInfoWrapper.getDataSetNameList(cardApplicationID); response.setDataSetNameList(dataSetNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetCreate function creates a new data set in the card application addressed with the * ConnectionHandle (or otherwise in a previously selected data set if this is implemented as a DF). * See BSI-TR-03112-4, version 1.1.2, section 3.4.2. * * @param request DataSetCreate * @return DataSetCreateResponse */ @Override public DataSetCreateResponse dataSetCreate(DataSetCreate request) { return WSHelper.makeResponse(DataSetCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The DataSetSelect function selects a data set in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.4.3. * * @param request DataSetSelect * @return DataSetSelectResponse */ @Override public DataSetSelectResponse dataSetSelect(DataSetSelect request) { DataSetSelectResponse response = WSHelper.makeResponse(DataSetSelectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dataSetName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dataSetName, NamedDataServiceActionName.DATA_SET_SELECT); byte[] fileID = dataSetInfo.getDataSetPath().getEfIdOrPath(); byte[] slotHandle = connectionHandle.getSlotHandle(); CardResponseAPDU result = CardUtils.selectFileWithOptions(env.getDispatcher(), slotHandle, fileID, null, CardUtils.FCP_RESPONSE_DATA); if (result != null) { cardStateEntry.setFCPOfSelectedEF(new FCP(result.getData())); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetDelete function deletes a data set of a card application on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.4.4. * * @param request DataSetDelete * @return DataSetDeleteResponse */ @Override public DataSetDeleteResponse dataSetDelete(DataSetDelete request) { DataSetDeleteResponse response = WSHelper.makeResponse(DataSetDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName, NamedDataServiceActionName.DATA_SET_DELETE); DataSetInfoType dataSet = cardInfoWrapper.getDataSet(dataSetName, cardApplicationID); if (dataSet == null) { throw new NamedEntityNotFoundException("The data set " + dataSetName + " does not exist."); } byte[] path = dataSet.getDataSetPath().getEfIdOrPath(); int len = path.length; byte[] fid = new byte[] {path[len - 2], path[len - 1]}; DeleteFile delFile = new DeleteFile.ChildFile(fid); delFile.transmit(env.getDispatcher(), connectionHandle.getSlotHandle()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The function DSIList supplies the list of the DSI (Data Structure for Interoperability) which exist in the * selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.5. <br> * <br> * Prerequisites: <br> * - a connection to a card application has been established <br> * - a data set has been selected <br> * * @param request DSIList * @return DSIListResponse */ @Override public DSIListResponse dsiList(DSIList request) { DSIListResponse response = WSHelper.makeResponse(DSIListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF selected."); } DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_LIST); DSINameListType dsiNameList = new DSINameListType(); for (DSIType dsi : dataSet.getDSI()) { dsiNameList.getDSIName().add(dsi.getDSIName()); } response.setDSINameList(dsiNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSICreate function creates a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.6. * <br> * <br> * Preconditions: <br> * - Connection to a card application established via CardApplicationConnect <br> * - A data set has been selected with DataSetSelect <br> * - The DSI does not exist in the data set. <br> * * @param request DSICreate * @return DSICreateResponse */ @Override public DSICreateResponse dsiCreate(DSICreate request) { DSICreateResponse response = WSHelper.makeResponse(DSICreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); byte[] dsiContent = request.getDSIContent(); Assert.assertIncorrectParameter(dsiContent, "The parameter DSIContent is empty."); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); if (dsi != null) { throw new NameExistsException("There is already an DSI with the name " + dsiName + " in the current EF."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No data set for writing selected."); } else { DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_CREATE); DataElements dElements = cardStateEntry.getFCPOfSelectedEF().getDataElements(); if (dElements.isTransparent()) { WriteBinary writeBin = new WriteBinary(WriteBinary.INS_WRITE_BINARY_DATA, (byte) 0x00, (byte) 0x00, dsiContent); writeBin.transmit(env.getDispatcher(), slotHandle); } else if (dElements.isCyclic()) { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_PREVIOUS, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } else { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_LAST, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIDelete function deletes a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.7. * * @param request DSIDelete * @return DSIDeleteResponse */ @Override public DSIDeleteResponse dsiDelete(DSIDelete request) { DSIDeleteResponse response = WSHelper.makeResponse(DSIDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); DataSetInfoType dSet = cardInfoWrapper.getDataSetByFid(cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, connectionHandle.getCardApplication(), dSet.getDataSetName(), NamedDataServiceActionName.DSI_DELETE); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); // We have to define some allowed answers because if the file has an write operation counter we wont get an // 9000 response. ArrayList<byte[]> responses = new ArrayList<byte[]>() { { add(new byte[] {(byte) 0x90, (byte) 0x00}); add(new byte[] {(byte) 0x63, (byte) 0xC1}); add(new byte[] {(byte) 0x63, (byte) 0xC2}); add(new byte[] {(byte) 0x63, (byte) 0xC3}); add(new byte[] {(byte) 0x63, (byte) 0xC4}); add(new byte[] {(byte) 0x63, (byte) 0xC5}); add(new byte[] {(byte) 0x63, (byte) 0xC6}); add(new byte[] {(byte) 0x63, (byte) 0xC7}); add(new byte[] {(byte) 0x63, (byte) 0xC8}); add(new byte[] {(byte) 0x63, (byte) 0xC9}); add(new byte[] {(byte) 0x63, (byte) 0xCA}); add(new byte[] {(byte) 0x63, (byte) 0xCB}); add(new byte[] {(byte) 0x63, (byte) 0xCC}); add(new byte[] {(byte) 0x63, (byte) 0xCD}); add(new byte[] {(byte) 0x63, (byte) 0xCE}); add(new byte[] {(byte) 0x63, (byte) 0xCF}); } }; if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) { EraseRecord rmRecord = new EraseRecord(dsi.getDSIPath().getIndex()[0], EraseRecord.ERASE_JUST_P1); rmRecord.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } else { // NOTE: Erase binary allows to erase only everything after the offset or everything in front of the offset. // currently erasing everything after the offset is used. EraseBinary rmBinary = new EraseBinary((byte) 0x00, (byte) 0x00, dsi.getDSIPath().getIndex()); rmBinary.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } } catch (ECardException e) { logger.error(e.getMessage(), e); response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIWrite function changes the content of a DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.8. * For clarification this method updates an existing DSI and does not create a new one. * * The precondition for this method is that a connection to a card application was established and a data set was * selected. Furthermore the DSI exists already. * * @param request DSIWrite * @return DSIWriteResponse */ @Override public DSIWriteResponse dsiWrite(DSIWrite request) { DSIWriteResponse response = WSHelper.makeResponse(DSIWriteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); byte[] updateData = request.getDSIContent(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); Assert.assertIncorrectParameter(updateData, "The parameter DSIContent is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_WRITE); if (! Arrays.equals(dataSetInfo.getDataSetPath().getEfIdOrPath(), cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) { throw new PrerequisitesNotSatisfiedException("The currently selected data set does not contain the DSI " + "to be updated."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF with DSI selected."); } else if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isTransparent()) { // currently assuming that the index encodes the offset byte[] index = dsi.getDSIPath().getIndex(); UpdateBinary updateBin = new UpdateBinary(index[0], index[1], updateData); updateBin.transmit(env.getDispatcher(), slotHandle); } else { // currently assuming that the index encodes the record number byte index = dsi.getDSIPath().getIndex()[0]; UpdateRecord updateRec = new UpdateRecord(index, updateData); updateRec.transmit(env.getDispatcher(), slotHandle); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIRead function reads out the content of a specific DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.9. * * @param request DSIRead * @return DSIReadResponse */ @Override public DSIReadResponse dsiRead(DSIRead request) { DSIReadResponse response = WSHelper.makeResponse(DSIReadResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_READ); byte[] slotHandle = connectionHandle.getSlotHandle(); // throws a null pointer if no ef is selected byte[] fileContent = CardUtils.readFile(cardStateEntry.getFCPOfSelectedEF(), env.getDispatcher(), slotHandle); response.setDSIContent(fileContent); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Encipher function encrypts a transmitted plain text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.1. * * @param request Encipher * @return EncipherResponse */ @Override public EncipherResponse encipher(Encipher request) { EncipherResponse response = WSHelper.makeResponse(EncipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] plainText = request.getPlainText(); Assert.assertIncorrectParameter(plainText, "The parameter PlainText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Encipher)) { response = protocol.encipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Encipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Decipher function decrypts a given cipher text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.2. * * @param request Decipher * @return DecipherResponse */ @Override public DecipherResponse decipher(Decipher request) { DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] cipherText = request.getCipherText(); Assert.assertIncorrectParameter(cipherText, "The parameter CipherText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Decipher)) { response = protocol.decipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Decipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The GetRandom function returns a random number which is suitable for authentication with the DID addressed with * DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.5.3. * * @param request GetRandom * @return GetRandomResponse */ @Override public GetRandomResponse getRandom(GetRandom request) { GetRandomResponse response = WSHelper.makeResponse(GetRandomResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.GetRandom)) { response = protocol.getRandom(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("GetRandom", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Hash function calculates the hash value of a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.4. * * @param request Hash * @return HashResponse */ @Override public HashResponse hash(Hash request) { HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Hash)) { response = protocol.hash(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Hash", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Sign function signs a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.5. * * @param request Sign * @return SignResponse */ @Override public SignResponse sign(Sign request) { SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Sign)) { response = protocol.sign(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Sign", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifySignature function verifies a digital signature. * See BSI-TR-03112-4, version 1.1.2, section 3.5.6. * * @param request VerifySignature * @return VerifySignatureResponse */ @Override public VerifySignatureResponse verifySignature(VerifySignature request) { VerifySignatureResponse response = WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] signature = request.getSignature(); Assert.assertIncorrectParameter(signature, "The parameter Signature is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifySignature)) { response = protocol.verifySignature(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifySignature", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifyCertificate function validates a given certificate. * See BSI-TR-03112-4, version 1.1.2, section 3.5.7. * * @param request VerifyCertificate * @return VerifyCertificateResponse */ @Override public VerifyCertificateResponse verifyCertificate(VerifyCertificate request) { VerifyCertificateResponse response = WSHelper.makeResponse(VerifyCertificateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] certificate = request.getCertificate(); Assert.assertIncorrectParameter(certificate, "The parameter Certificate is empty."); String certificateType = request.getCertificateType(); Assert.assertIncorrectParameter(certificateType, "The parameter CertificateType is empty."); String rootCert = request.getRootCert(); Assert.assertIncorrectParameter(rootCert, "The parameter RootCert is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifyCertificate)) { response = protocol.verifyCertificate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifyCertificate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDList function returns a list of the existing DIDs in the card application addressed by the * ConnectionHandle or the ApplicationIdentifier element within the Filter. * See BSI-TR-03112-4, version 1.1.2, section 3.6.1. * * @param request DIDList * @return DIDListResponse */ @Override public DIDListResponse didList(DIDList request) { DIDListResponse response = WSHelper.makeResponse(DIDListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] appId = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); Assert.securityConditionApplication(cardStateEntry, appId, DifferentialIdentityServiceActionName.DID_LIST); byte[] applicationIDFilter = null; String objectIDFilter = null; String applicationFunctionFilter = null; DIDQualifierType didQualifier = request.getFilter(); if (didQualifier != null) { applicationIDFilter = didQualifier.getApplicationIdentifier(); objectIDFilter = didQualifier.getObjectIdentifier(); applicationFunctionFilter = didQualifier.getApplicationFunction(); } /* * Filter by ApplicationIdentifier. * [TR-03112-4] Allows specifying an application identifier. If this element is present all * DIDs within the specified card application are returned no matter which card application * is currently selected. */ CardApplicationWrapper cardApplication; if (applicationIDFilter != null) { cardApplication = cardStateEntry.getInfo().getCardApplication(applicationIDFilter); Assert.assertIncorrectParameter(cardApplication, "The given CardApplication cannot be found."); } else { cardApplication = cardStateEntry.getCurrentCardApplication(); } List<DIDInfoType> didInfos = new ArrayList<DIDInfoType>(cardApplication.getDIDInfoList()); /* * Filter by ObjectIdentifier. * [TR-03112-4] Allows specifying a protocol OID (cf. [TR-03112-7]) such that only DIDs * which support a given protocol are listed. */ if (objectIDFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (!next.getDifferentialIdentity().getDIDProtocol().equals(objectIDFilter)) { it.remove(); } } } /* * Filter by ApplicationFunction. * [TR-03112-4] Allows filtering for DIDs, which support a specific cryptographic operation. * The bit string is coded as the SupportedOperations-element in [ISO7816-15]. */ if (applicationFunctionFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (next.getDifferentialIdentity().getDIDMarker().getCryptoMarker() == null) { it.remove(); } else { iso.std.iso_iec._24727.tech.schema.CryptoMarkerType rawMarker; rawMarker = next.getDifferentialIdentity().getDIDMarker().getCryptoMarker(); CryptoMarkerType cryptoMarker = new CryptoMarkerType(rawMarker); AlgorithmInfoType algInfo = cryptoMarker.getAlgorithmInfo(); if (! algInfo.getSupportedOperations().contains(applicationFunctionFilter)) { it.remove(); } } } } DIDNameListType didNameList = new DIDNameListType(); for (DIDInfoType didInfo : didInfos) { didNameList.getDIDName().add(didInfo.getDifferentialIdentity().getDIDName()); } response.setDIDNameList(didNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDCreate function creates a new differential identity in the card application addressed with ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.6.2. * * @param request DIDCreate * @return DIDCreateResponse */ @Override public DIDCreateResponse didCreate(DIDCreate request) { return WSHelper.makeResponse(DIDCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The public information for a DID is read with the DIDGet function. * See BSI-TR-03112-4, version 1.1.2, section 3.6.3. * * @param request DIDGet * @return DIDGetResponse */ @Override public DIDGetResponse didGet(DIDGet request) { DIDGetResponse response = WSHelper.makeResponse(DIDGetResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); // handle must be requested without application, as it is irrelevant for this call CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle); response.setDIDStructure(didStructure); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDUpdate function creates a new key (marker) for the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.4. * * @param request DIDUpdate * @return DIDUpdateResponse */ @Override public DIDUpdateResponse didUpdate(DIDUpdate request) { DIDUpdateResponse response = WSHelper.makeResponse(DIDUpdateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDUpdateDataType didUpdateData = request.getDIDUpdateData(); Assert.assertIncorrectParameter(didUpdateData, "The parameter DIDUpdateData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_UPDATE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDUpdate)) { response = protocol.didUpdate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDUpdate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDDelete function deletes the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.5. * * @param request DIDDelete * @return DIDDeleteResponse */ @Override public DIDDeleteResponse didDelete(DIDDelete request) { DIDDeleteResponse response = WSHelper.makeResponse(DIDDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_DELETE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDDelete)) { response = protocol.didDelete(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDDelete", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDAuthenticate function can be used to execute an authentication protocol using a DID addressed by DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.6. * * @param request DIDAuthenticate * @return DIDAuthenticateResponse */ @Override public DIDAuthenticateResponse didAuthenticate(DIDAuthenticate request) { DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); DIDAuthenticationDataType didAuthenticationData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationData, "The parameter AuthenticationProtocolData is empty."); String protocolURI = didAuthenticationData.getProtocol(); // FIXME: workaround for missing protocol URI from eID-Servers if (protocolURI == null) { logger.warn("ProtocolURI was null"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } else if (protocolURI.equals("urn:oid:1.0.24727.3.0.0.7.2")) { logger.warn("ProtocolURI was urn:oid:1.0.24727.3.0.0.7.2"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } didAuthenticationData.setProtocol(protocolURI); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDAuthenticate)) { response = protocol.didAuthenticate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDAuthenticate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ACLList function returns the access control list for the stated target object (card application, data set, DID). * See BSI-TR-03112-4, version 1.1.2, section 3.7.1. * * @param request ACLList * @return ACLListResponse */ @Override public ACLListResponse aclList(ACLList request) { ACLListResponse response = WSHelper.makeResponse(ACLListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); TargetNameType targetName = request.getTargetName(); Assert.assertIncorrectParameter(targetName, "The parameter TargetName is empty."); // get the target values, according to the schema only one must exist, we pick the first existing ;-) byte[] targetAppId = targetName.getCardApplicationName(); String targetDataSet = targetName.getDataSetName(); String targetDid = targetName.getDIDName(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] handleAppId = connectionHandle.getCardApplication(); if (targetDataSet != null) { DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(targetDataSet, handleAppId); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); response.setTargetACL(cardInfoWrapper.getDataSet(targetDataSet, handleAppId).getDataSetACL()); } else if (targetDid != null) { DIDInfoType didInfo = cardInfoWrapper.getDIDInfo(targetDid, handleAppId); Assert.assertNamedEntityNotFound(didInfo, "The given DIDInfo cannot be found."); //TODO Check security condition ? response.setTargetACL(cardInfoWrapper.getDIDInfo(targetDid, handleAppId).getDIDACL()); } else if (targetAppId != null) { CardApplicationWrapper cardApplication = cardInfoWrapper.getCardApplication(targetAppId); Assert.assertNamedEntityNotFound(cardApplication, "The given CardApplication cannot be found."); Assert.securityConditionApplication(cardStateEntry, targetAppId, AuthorizationServiceActionName.ACL_LIST); response.setTargetACL(cardInfoWrapper.getCardApplication(targetAppId).getCardApplicationACL()); } else { throw new IncorrectParameterException("The given TargetName is invalid."); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * An access rule in the access control list is modified with the ACLModify function. * See BSI-TR-03112-4, version 1.1.2, section 3.7.2. * * @param request ACLModify * @return ACLModifyResponse */ @Override public ACLModifyResponse aclModify(ACLModify request) { return WSHelper.makeResponse(ACLModifyResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Sets the GUI. * * @param uc User consent */ public void setGUI(UserConsent uc) { this.userConsent = uc; } /** * Returns a list of ConnectionHandles. * * @return List of ConnectionHandles */ public List<ConnectionHandleType> getConnectionHandles() { ConnectionHandleType handle = new ConnectionHandleType(); Set<CardStateEntry> entries = states.getMatchingEntries(handle); ArrayList<ConnectionHandleType> result = new ArrayList<ConnectionHandleType>(entries.size()); for (CardStateEntry entry : entries) { result.add(entry.handleCopy()); } return result; } /** * Removes a finished protocol from the SAL instance. * * @param handle Connection Handle * @param protocolURI Protocol URI * @param protocol Protocol * @throws UnknownConnectionHandleException */ public void removeFinishedProtocol(ConnectionHandleType handle, String protocolURI, SALProtocol protocol) throws UnknownConnectionHandleException { if (protocol.isFinished()) { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); entry.removeProtocol(protocolURI); } } private SALProtocol getProtocol(ConnectionHandleType handle, String protocolURI) throws UnknownProtocolException, UnknownConnectionHandleException { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); SALProtocol protocol = entry.getProtocol(protocolURI); if (protocol == null) { try { protocol = protocolSelector.getSALProtocol(protocolURI); entry.setProtocol(protocolURI, protocol); } catch (AddonNotFoundException ex) { throw new UnknownProtocolException("The protocol URI '" + protocolURI + "' is not available."); } } protocol.getInternalData().put("cardState", entry); return protocol; } }
import java.util.ArrayList; import java.util.List; public class Hand { private List<Card> cards = new ArrayList<Card>(); // Constructor public Hand(ArrayList<Card> cards) { this.cards = cards; } // Called when player wants to hit public void addCard(Card card) { cards.add(card); } // Returns an array of length 1 or 2 containing possible values of the hand public int[] getValues() { int val0 = 0; // Hand value assuming first ace is valued at 1 int val1 = 0; // Hand value assuming first ace is valued at 11 boolean hasAce = false; int[] cardValue; // If Ace if(cardValue.length == 2) { // If Ace already exists in hand, just add 1 if(hasAce) { val0 += cardValue[0]; val1 += cardValue[0]; } else { val0 += cardValue[0]; val1 += cardValue[1]; hasAce = true; } } // Otherwise single-value cards (2-10, J, Q, K) else { val0 += cardValue[0]; val1 += cardValue[0]; } if(val0 == val1) { return new int[] { val0 }; } else { return new int[] {val0, val1}; } } // TODO public Hand split() { if(cards.size() != 2) { return null; } Hand[] newHands = new Hand[2]; ArrayList<Card> cardForHand0 = new ArrayList<Card>(); ArrayList<Card> cardForHand1 = new ArrayList<Card>(); newHands[0] = new Hand(); } }
import com.sun.star.uno.UnoRuntime; import com.sun.star.accessibility.XAccessible; import com.sun.star.accessibility.XAccessibleContext; import com.sun.star.accessibility.XAccessibleSelection; import com.sun.star.lang.IndexOutOfBoundsException; import javax.swing.*; import java.awt.*; import java.util.Vector; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * Display a dialog with a list-box of children and select/deselect buttons */ class SelectionDialog extends JDialog implements ActionListener { public SelectionDialog (AccTreeNode aNode) { super (AccessibilityWorkBench.Instance()); maNode = aNode; Layout(); } /** build dialog */ protected void Layout () { setTitle( "Select" ); // vertical stacking of the elements Container aContent = getContentPane(); // label with explanation aContent.add( new JLabel( "Select/Deselect child elements" ), BorderLayout.NORTH ); // the JListBox maChildrenSelector = new JList (GetChildrenList()); maChildrenSelector.setPreferredSize (new Dimension (500,300)); aContent.add (maChildrenSelector, BorderLayout.CENTER); maChildrenSelector.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); JPanel aButtons = new JPanel(); aButtons.setLayout( new FlowLayout() ); JButton aButton; aButton = new JButton( "Select" ); aButton.setActionCommand( "Select" ); aButton.addActionListener( this ); aButtons.add( aButton ); aButton = new JButton( "Deselect" ); aButton.setActionCommand( "Deselect" ); aButton.addActionListener( this ); aButtons.add( aButton ); aButton = new JButton( "Select all" ); aButton.setActionCommand( "Select all" ); aButton.addActionListener( this ); aButtons.add( aButton ); aButton = new JButton( "Clear Selection" ); aButton.setActionCommand( "Clear Selection" ); aButton.addActionListener( this ); aButtons.add( aButton ); aButton = new JButton( "Close" ); aButton.setActionCommand( "Close" ); aButton.addActionListener( this ); aButtons.add( aButton ); // add Panel with buttons aContent.add( aButtons, BorderLayout.SOUTH ); setSize( getPreferredSize() ); } /** Get a list of all children */ private Vector GetChildrenList () { mxSelection = maNode.getSelection(); XAccessibleContext xContext = maNode.getContext(); int nCount = xContext.getAccessibleChildCount(); Vector aChildVector = new Vector(); for(int i = 0; i < nCount; i++) { try { XAccessible xChild = xContext.getAccessibleChild(i); XAccessibleContext xChildContext = xChild.getAccessibleContext(); aChildVector.add( i + " " + xChildContext.getAccessibleName()); } catch( IndexOutOfBoundsException e ) { aChildVector.add( "ERROR: IndexOutOfBoundsException" ); } } return aChildVector; } void close () { hide(); dispose(); } void select() { try { mxSelection.selectAccessibleChild (maChildrenSelector.getSelectedIndex()); } catch( IndexOutOfBoundsException e ) { JOptionPane.showMessageDialog( AccessibilityWorkBench.Instance(), "Can't select: IndexOutofBounds", "Error in selectAccessibleChild", JOptionPane.ERROR_MESSAGE); } } void deselect() { try { mxSelection.deselectAccessibleChild( maChildrenSelector.getSelectedIndex()); } catch( IndexOutOfBoundsException e ) { JOptionPane.showMessageDialog( AccessibilityWorkBench.Instance(), "Can't deselect: IndexOutofBounds", "Error in deselectAccessibleChild", JOptionPane.ERROR_MESSAGE); } } void selectAll() { mxSelection.selectAllAccessibleChildren(); } void clearSelection() { mxSelection.clearAccessibleSelection(); } public void actionPerformed(ActionEvent e) { String sCommand = e.getActionCommand(); if( "Close".equals( sCommand ) ) close(); else if ( "Select".equals( sCommand ) ) select(); else if ( "Deselect".equals( sCommand ) ) deselect(); else if ( "Clear Selection".equals( sCommand ) ) clearSelection(); else if ( "Select all".equals( sCommand ) ) selectAll(); } private JList maChildrenSelector; private XAccessibleSelection mxSelection; private AccTreeNode maNode; }
package controllers; import javax.inject.Inject; import javax.xml.namespace.QName; import com.fasterxml.jackson.databind.JsonNode; import com.mysema.query.Tuple; import com.mysema.query.sql.SQLQuery; import com.mysema.query.sql.SQLSubQuery; import com.mysema.query.support.Expressions; import com.mysema.query.types.Expression; import com.mysema.query.types.QTuple; import com.mysema.query.types.expr.BooleanExpression; import com.mysema.query.types.expr.NumberExpression; import com.mysema.query.types.path.NumberPath; import com.mysema.query.types.path.StringPath; import com.mysema.query.types.template.BooleanTemplate; import nl.idgis.dav.model.Resource; import nl.idgis.dav.model.ResourceDescription; import nl.idgis.dav.model.ResourceProperties; import nl.idgis.dav.model.DefaultResource; import nl.idgis.dav.model.DefaultResourceDescription; import nl.idgis.dav.model.DefaultResourceProperties; import nl.idgis.publisher.database.QSourceDatasetVersion; import nl.idgis.publisher.database.QSourceDatasetVersionColumn; import nl.idgis.publisher.metadata.MetadataDocument; import nl.idgis.publisher.metadata.MetadataDocumentFactory; import nl.idgis.publisher.xml.exceptions.NotFound; import nl.idgis.publisher.xml.exceptions.QueryFailure; import play.Logger; import play.api.mvc.Handler; import play.api.mvc.RequestHeader; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import util.MetadataConfig; import util.QueryDSL; import util.QueryDSL.Transaction; import static nl.idgis.publisher.database.QDataset.dataset; import static nl.idgis.publisher.database.QDatasetColumn.datasetColumn; import static nl.idgis.publisher.database.QSourceDataset.sourceDataset; import static nl.idgis.publisher.database.QSourceDatasetMetadata.sourceDatasetMetadata; import static nl.idgis.publisher.database.QSourceDatasetMetadataAttachment.sourceDatasetMetadataAttachment; import static nl.idgis.publisher.database.QSourceDatasetVersion.sourceDatasetVersion; import static nl.idgis.publisher.database.QSourceDatasetVersionColumn.sourceDatasetVersionColumn; import static nl.idgis.publisher.database.QPublishedServiceDataset.publishedServiceDataset; import static nl.idgis.publisher.database.QPublishedService.publishedService; import static nl.idgis.publisher.database.QEnvironment.environment; import static nl.idgis.publisher.database.QDatasetCopy.datasetCopy; import static nl.idgis.publisher.database.QDatasetView.datasetView; import java.io.IOException; import java.sql.Timestamp; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.Collectors; public class DatasetMetadata extends AbstractMetadata { private final MetadataDocumentFactory mdf; private final Pattern urlPattern; @Inject public DatasetMetadata(MetadataConfig config, QueryDSL q) throws Exception { this(config, q, new MetadataDocumentFactory(), "/"); } public DatasetMetadata(MetadataConfig config, QueryDSL q, MetadataDocumentFactory mdf, String prefix) { super(config, q, prefix); this.mdf = mdf; urlPattern = Pattern.compile(".*/(.*)(\\?.*)?$"); } @Override public DatasetMetadata withPrefix(String prefix) { return new DatasetMetadata(config, q, mdf, prefix); } private SQLQuery fromNonPublishedSourceDataset(Transaction tx) { return joinSourceDatasetVersion( tx.query().from(sourceDataset) .join(sourceDatasetMetadata).on(sourceDatasetMetadata.sourceDatasetId.eq(sourceDataset.id)) .where(new SQLSubQuery().from(dataset) .where(dataset.sourceDatasetId.eq(sourceDataset.id)) .where(isPublishedDataset()) .notExists())); } private SQLQuery fromSourceDataset(Transaction tx) { return joinSourceDatasetVersion( tx.query().from(sourceDataset) .join(sourceDatasetMetadata).on(sourceDatasetMetadata.sourceDatasetId.eq(sourceDataset.id))); } private SQLQuery joinSourceDatasetVersion(SQLQuery query) { query .join(sourceDatasetVersion).on(sourceDatasetVersion.sourceDatasetId.eq(sourceDataset.id)) .where(sourceDatasetVersion.id.in(new SQLSubQuery().from(sourceDatasetVersion) .where(sourceDatasetVersion.sourceDatasetId.eq(sourceDataset.id)) .list(sourceDatasetVersion.id.max()))); if(isTrusted()) { return query; } else { return query.where(sourceDatasetVersion.metadataConfidential.isFalse()); } } private SQLQuery fromPublishedDataset(Transaction tx) { return joinSourceDatasetVersion(tx.query().from(dataset) .join(sourceDataset).on(sourceDataset.id.eq(dataset.sourceDatasetId)) .join(sourceDatasetMetadata).on(sourceDatasetMetadata.sourceDatasetId.eq(sourceDataset.id)) .where(isPublishedDataset())); } private SQLQuery fromDataset(Transaction tx) { return joinSourceDatasetVersion(tx.query().from(dataset) .join(sourceDataset).on(sourceDataset.id.eq(dataset.sourceDatasetId)) .join(sourceDatasetMetadata).on(sourceDatasetMetadata.sourceDatasetId.eq(sourceDataset.id))); } private BooleanExpression isPublishedDataset() { return new SQLSubQuery().from(publishedServiceDataset) .where(publishedServiceDataset.datasetId.eq(dataset.id)) .exists(); } @Override public Optional<Resource> resource(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Optional<Resource> optionalDataset = datasetResource(id, tx); if(optionalDataset.isPresent()) { return optionalDataset; } else { if(config.getIncludeSourceDatasetMetadata()) { return sourceDatasetResource(id, tx); } else { Optional<Resource> emptyOptional = Optional.empty(); return emptyOptional; } } })); } private Optional<Resource> sourceDatasetResource(String id, Transaction tx) { return Optional.ofNullable(fromSourceDataset(tx) .where(sourceDataset.metadataFileIdentification.eq(id)) .singleResult( sourceDataset.metadataIdentification, sourceDatasetMetadata.sourceDatasetId, sourceDatasetMetadata.document)) .map(datasetTuple -> tupleToDatasetResource( tx, datasetTuple, datasetTuple.get(sourceDatasetMetadata.sourceDatasetId), null, id, datasetTuple.get(sourceDataset.metadataIdentification))); } private Optional<Resource> datasetResource(String id, Transaction tx) throws Exception { return Optional.ofNullable(fromDataset(tx) .where(dataset.metadataFileIdentification.eq(id)) .singleResult( dataset.id, dataset.metadataIdentification, sourceDatasetMetadata.sourceDatasetId, sourceDatasetMetadata.document)) .map(datasetTuple -> tupleToDatasetResource( tx, datasetTuple, datasetTuple.get(sourceDatasetMetadata.sourceDatasetId), datasetTuple.get(dataset.id), id, datasetTuple.get(dataset.metadataIdentification))); } private List<Tuple> datasetColumnAliases(Transaction tx, Expression<?> datasetRel, NumberPath<Integer> datasetRelId, StringPath datasetRelName, int datasetId) { final QSourceDatasetVersionColumn sourceDatasetVersionColumnSub = new QSourceDatasetVersionColumn("source_dataset_version_column_sub"); final QSourceDatasetVersion sourceDatasetVersionSub = new QSourceDatasetVersion("source_dataset_version_sub"); return tx.query().from(datasetRel) .join(dataset).on(dataset.id.eq(datasetRelId)) .join(sourceDatasetVersionColumn).on(sourceDatasetVersionColumn.name.eq(datasetRelName)) .join(sourceDatasetVersion).on(sourceDatasetVersion.id.eq(sourceDatasetVersionColumn.sourceDatasetVersionId) .and(dataset.sourceDatasetId.eq(sourceDatasetVersion.sourceDatasetId))) .where(datasetRelId.eq(datasetId)) .where(new SQLSubQuery().from(sourceDatasetVersionColumnSub) .join(sourceDatasetVersionSub).on(sourceDatasetVersionSub.id.eq(sourceDatasetVersionColumnSub.sourceDatasetVersionId)) .where(sourceDatasetVersionColumnSub.name.eq(sourceDatasetVersionColumn.name)) .where(sourceDatasetVersionColumnSub.sourceDatasetVersionId.gt(sourceDatasetVersionColumn.sourceDatasetVersionId)) .where(sourceDatasetVersionSub.sourceDatasetId.eq(dataset.sourceDatasetId)) .notExists()) .where(sourceDatasetVersionColumn.alias.isNotNull()) .orderBy(sourceDatasetVersionColumn.index.desc()) .list(sourceDatasetVersionColumn.name, sourceDatasetVersionColumn.alias); } private Resource tupleToDatasetResource(Transaction tx, Tuple datasetTuple, int sourceDatasetId, Integer datasetId, String fileIdentifier, String datasetIdentifier) { try { MetadataDocument metadataDocument = mdf.parseDocument(datasetTuple.get(sourceDatasetMetadata.document)); metadataDocument.removeStylesheet(); stylesheet("datasets").ifPresent(metadataDocument::setStylesheet); metadataDocument.setDatasetIdentifier(datasetIdentifier); metadataDocument.setFileIdentifier(fileIdentifier); if(!isTrusted()) { metadataDocument.removeAdditionalPointOfContacts(); } Map<String, Integer> attachments = tx.query().from(sourceDatasetMetadataAttachment) .where(sourceDatasetMetadataAttachment.sourceDatasetId.eq(sourceDatasetId)) .list( sourceDatasetMetadataAttachment.id, sourceDatasetMetadataAttachment.identification) .stream() .collect(Collectors.toMap( t -> t.get(sourceDatasetMetadataAttachment.identification), t -> t.get(sourceDatasetMetadataAttachment.id))); for(String supplementalInformation : metadataDocument.getSupplementalInformation()) { int separator = supplementalInformation.indexOf("|"); if(separator != -1) { String type = supplementalInformation.substring(0, separator); String url = supplementalInformation.substring(separator + 1).trim().replace('\\', '/'); String fileName; Matcher urlMatcher = urlPattern.matcher(url); if(urlMatcher.find()) { fileName = urlMatcher.group(1); } else { fileName = "download"; } if(attachments.containsKey(supplementalInformation)) { String updatedSupplementalInformation = type + "|" + routes.Attachment.get(attachments.get(supplementalInformation).toString(), fileName) .absoluteURL(false, config.getHost()); metadataDocument.updateSupplementalInformation( supplementalInformation, updatedSupplementalInformation); } else { metadataDocument.removeSupplementalInformation(supplementalInformation); } } } List<String> browseGraphics = metadataDocument.getDatasetBrowseGraphics(); for(String browseGraphic : browseGraphics) { if(attachments.containsKey(browseGraphic)) { String url = browseGraphic.trim().replace('\\', '/'); String fileName; Matcher urlMatcher = urlPattern.matcher(url); if(urlMatcher.find()) { fileName = urlMatcher.group(1); } else { fileName = "preview"; } String updatedbrowseGraphic = routes.Attachment.get(attachments.get(browseGraphic).toString(), fileName) .absoluteURL(false, config.getHost()); metadataDocument.updateDatasetBrowseGraphic(browseGraphic, updatedbrowseGraphic); } } metadataDocument.removeServiceLinkage(); Consumer<List<Tuple>> columnAliasWriter = columnTuples -> { if(columnTuples.isEmpty()) { return; } StringBuilder textAlias = new StringBuilder("INHOUD ATTRIBUTENTABEL:"); for(Tuple columnTuple : columnTuples) { textAlias .append(" ") .append(columnTuple.get(sourceDatasetVersionColumn.name)) .append(": ") .append(columnTuple.get(sourceDatasetVersionColumn.alias)); } try { metadataDocument.addProcessStep(textAlias.toString()); } catch(NotFound nf) { throw new RuntimeException(nf); } }; if(datasetId == null) { columnAliasWriter.accept( tx.query().from(sourceDatasetVersionColumn) .where(sourceDatasetVersionColumn.sourceDatasetVersionId.eq( new SQLSubQuery().from(sourceDatasetVersion) .where(sourceDatasetVersion.sourceDatasetId.eq(sourceDatasetId)) .unique(sourceDatasetVersion.id.max()))) .where(sourceDatasetVersionColumn.alias.isNotNull()) .orderBy(sourceDatasetVersionColumn.index.desc()) .list(sourceDatasetVersionColumn.name, sourceDatasetVersionColumn.alias)); } else { final QSourceDatasetVersionColumn sourceDatasetVersionColumnSub = new QSourceDatasetVersionColumn("source_dataset_version_column_sub"); List<Tuple> datasetCopyAliases = datasetColumnAliases( tx, datasetCopy, datasetCopy.datasetId, datasetCopy.name, datasetId); if(datasetCopyAliases.isEmpty()) { columnAliasWriter.accept( datasetColumnAliases( tx, datasetView, datasetView.datasetId, datasetView.name, datasetId)); } else { columnAliasWriter.accept(datasetCopyAliases); } SQLQuery serviceQuery = tx.query().from(publishedService) .join(publishedServiceDataset).on(publishedServiceDataset.serviceId.eq(publishedService.serviceId)) .join(environment).on(environment.id.eq(publishedService.environmentId)); if(!isTrusted()) { // do not generate links to services with confidential content as these are inaccessible. serviceQuery.where(environment.confidential.isFalse()); } List<Tuple> serviceTuples = serviceQuery.where(publishedServiceDataset.datasetId.eq(datasetId)) .list( publishedService.content, environment.identification, environment.confidential, environment.url, publishedServiceDataset.layerName); if(!serviceTuples.isEmpty()) { config.getDownloadUrlPrefix().ifPresent(downloadUrlPrefix -> { if(config.getDownloadUrlDisplay()) { try { metadataDocument.addServiceLinkage(downloadUrlPrefix + fileIdentifier, "download", null); } catch(NotFound nf) { throw new RuntimeException(nf); } } }); } boolean confidential = true; int serviceTupleIndex = 0; for(int i = 0; i < serviceTuples.size(); i++) { boolean envConfidential = serviceTuples.get(i).get(environment.confidential); if(!envConfidential) { confidential = false; serviceTupleIndex = i; break; } } for(int i = 0; i < serviceTuples.size(); i++) { JsonNode serviceInfo = Json.parse(serviceTuples.get(i).get(publishedService.content)); String serviceName = serviceInfo.get("name").asText(); String scopedName = serviceTuples.get(i).get(publishedServiceDataset.layerName); if(i == serviceTupleIndex) { if(confidential) { config.getViewerUrlSecurePrefix().ifPresent(viewerUrlPrefix -> { try { metadataDocument.addServiceLinkage(viewerUrlPrefix + "/layer/" + serviceName + "/" + scopedName, "website", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } else { config.getViewerUrlPublicPrefix().ifPresent(viewerUrlPrefix -> { try { metadataDocument.addServiceLinkage(viewerUrlPrefix + "/layer/" + serviceName + "/" + scopedName, "website", null); } catch(NotFound nf) { throw new RuntimeException(nf); } }); } } String environmentUrl = serviceTuples.get(i).get(environment.url); // we only automatically generate browseGraphics // when none where provided by the source. if(browseGraphics.isEmpty()) { String linkage = getServiceLinkage(environmentUrl, serviceName, ServiceType.WMS); metadataDocument.addDatasetBrowseGraphic(linkage + config.getBrowseGraphicWmsRequest() + scopedName); } for(ServiceType serviceType : ServiceType.values()) { String linkage = getServiceLinkage(environmentUrl, serviceName, serviceType); String protocol = serviceType.getProtocol(); for(String spatialSchema : metadataDocument.getSpatialSchema()) { if(spatialSchema.equals("vector") || protocol.equals("OGC:WMS")) { metadataDocument.addServiceLinkage(linkage, protocol, scopedName); } } } } } return new DefaultResource("application/xml", metadataDocument.getContent()); } catch(Exception e) { throw new RuntimeException(e); } } @Override public Stream<ResourceDescription> descriptions() { if(config.getIncludeSourceDatasetMetadata()) { return q.withTransaction(tx -> Stream.concat( datasetDescriptions(tx), sourceDatasetDescriptions(tx))); } else { return q.withTransaction(this::datasetDescriptions); } } private Stream<ResourceDescription> sourceDatasetDescriptions(Transaction tx) { return fromNonPublishedSourceDataset(tx).list( sourceDataset.metadataFileIdentification, sourceDatasetVersion.metadataConfidential, sourceDatasetVersion.revision).stream() .map(tuple -> tupleToDatasetDescription(tuple, sourceDataset.metadataFileIdentification, false)); } private Stream<ResourceDescription> datasetDescriptions(Transaction tx) { return fromPublishedDataset(tx).list( dataset.metadataFileIdentification, sourceDatasetVersion.metadataConfidential, sourceDatasetVersion.revision).stream() .map(tuple -> tupleToDatasetDescription(tuple, dataset.metadataFileIdentification, true)); } private ResourceDescription tupleToDatasetDescription(Tuple tuple, Expression<String> identificationExpression, boolean published) { Timestamp createTime = tuple.get(sourceDatasetVersion.revision); boolean confidential = tuple.get(sourceDatasetVersion.metadataConfidential); return new DefaultResourceDescription( getName(tuple.get(identificationExpression)), new DefaultResourceProperties( false, createTime, resourceProperties(confidential, published))); } @Override public Optional<ResourceProperties> properties(String name) { return getId(name).flatMap(id -> q.withTransaction(tx -> { Optional<ResourceProperties> optionalProperties = datasetProperties(id, tx); if(optionalProperties.isPresent()) { return optionalProperties; } else { if(config.getIncludeSourceDatasetMetadata()) { return sourceDatasetProperties(id, tx); } else { Optional<ResourceProperties> emptyOptional = Optional.empty(); return emptyOptional; } } })); } private Optional<ResourceProperties> sourceDatasetProperties(String id, Transaction tx) { return tupleToDatasetProperties( fromSourceDataset(tx).where(sourceDataset.metadataFileIdentification.eq(id)), BooleanTemplate.FALSE); } private Optional<ResourceProperties> datasetProperties(String id, Transaction tx) { return tupleToDatasetProperties( fromDataset(tx).where(dataset.metadataFileIdentification.eq(id)), isPublishedDataset()); } private Optional<ResourceProperties> tupleToDatasetProperties(SQLQuery query, BooleanExpression isPublished) { final BooleanExpression isPublishedAliased = isPublished.as("is_published"); return Optional.ofNullable(query .singleResult(sourceDatasetVersion.revision, sourceDatasetVersion.metadataConfidential, isPublishedAliased)) .map(datasetTuple -> { Timestamp createTime = datasetTuple.get(sourceDatasetVersion.revision); boolean confidential = datasetTuple.get(sourceDatasetVersion.metadataConfidential); return new DefaultResourceProperties( false, createTime, resourceProperties(confidential, datasetTuple.get(isPublishedAliased))); }); } private Map<QName, String> resourceProperties(boolean confidential, boolean published) { Map<QName, String> properties = new HashMap<QName, String>(); properties.put(new QName("http://idgis.nl/geopublisher", "confidential"), "" + confidential); properties.put(new QName("http://idgis.nl/geopublisher", "published"), "" + published); return properties; } }
package com.pironet.tda; import com.pironet.tda.utils.HistogramTableModel; import com.pironet.tda.utils.IconFactory; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.regex.Matcher; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; /** * Parses SunJDK Thread Dumps. * Needs to be closed after use (so inner stream is closed). * * @author irockel */ public class SunJDKParser extends AbstractDumpParser { private MutableTreeNode nextDump = null; private Map threadStore = null; private int counter = 1; private int lineCounter = 0; private boolean foundClassHistograms = false; private boolean withCurrentTimeStamp = false; /** * Creates a new instance of SunJDKParser */ public SunJDKParser(BufferedReader bis, Map threadStore, int lineCounter, boolean withCurrentTimeStamp, int startCounter) { super(bis); this.threadStore = threadStore; this.withCurrentTimeStamp = withCurrentTimeStamp; this.lineCounter = lineCounter; this.counter = startCounter; } /** * returns true if at least one more dump available, already loads it * (this will be returned on next call of parseNext) */ public boolean hasMoreDumps() { nextDump = parseNext(); return(nextDump != null); } /** * @returns true, if a class histogram was found and added during parsing. */ public boolean isFoundClassHistograms() { return(foundClassHistograms); } /** * parse the next thread dump from the stream passed with the constructor. * @returns null if no more thread dumps were found. */ public MutableTreeNode parseNext() { if (nextDump != null) { MutableTreeNode tmpDump = nextDump; nextDump = null; return(tmpDump); } DefaultMutableTreeNode threadDump = null; ThreadDumpInfo overallTDI = null; DefaultMutableTreeNode catMonitors = null; DefaultMutableTreeNode catMonitorsLocks = null; DefaultMutableTreeNode catThreads = null; DefaultMutableTreeNode catLocking = null; DefaultMutableTreeNode catSleeping = null; DefaultMutableTreeNode catWaiting = null; try { Map threads = new HashMap(); overallTDI = new ThreadDumpInfo("Dump No. " + counter++, 0); if(withCurrentTimeStamp) { overallTDI.setStartTime((new Date(System.currentTimeMillis())).toString()); } threadDump = new DefaultMutableTreeNode(overallTDI); catThreads = new DefaultMutableTreeNode(new TableCategory("Threads", IconFactory.THREADS)); threadDump.add(catThreads); catWaiting = new DefaultMutableTreeNode(new TableCategory("Threads waiting for Monitors", IconFactory.THREADS_WAITING)); catSleeping = new DefaultMutableTreeNode(new TableCategory("Threads sleeping on Monitors", IconFactory.THREADS_SLEEPING)); catLocking = new DefaultMutableTreeNode(new TableCategory("Threads locking Monitors", IconFactory.THREADS_LOCKING)); // create category for monitors with disabled filtering. catMonitors = new DefaultMutableTreeNode(new TreeCategory("Monitors", IconFactory.MONITORS, false)); catMonitorsLocks = new DefaultMutableTreeNode(new TreeCategory("Monitors without locking thread", IconFactory.MONITORS_NOLOCKS, false)); String title = null; String dumpKey = null; StringBuffer content = null; StringBuffer lContent = null; StringBuffer sContent = null; StringBuffer wContent = null; int threadCount = 0; int waiting = 0; int locking = 0; int sleeping = 0; boolean locked = true; boolean finished = false; MonitorMap mmap = new MonitorMap(); Stack monitorStack = new Stack(); long startTime = 0; int singleLineCounter = 0; Matcher matched = null; while(getBis().ready() && !finished) { String line = getBis().readLine(); lineCounter++; singleLineCounter++; if(locked) { if(line.indexOf("Full thread dump") >= 0) { locked = false; if(!withCurrentTimeStamp) { overallTDI.setLogLine(lineCounter); if (startTime != 0) { startTime = 0; } else if (matched != null && matched.matches()) { String parsedStartTime = matched.group(1); if (isMillisTimeStamp()) { try { // the factor is a hack for a bug in oc4j timestamp printing (pattern timeStamp=2342342340) if (parsedStartTime.length() < 13) { startTime = Long.parseLong(parsedStartTime) * (long) Math.pow(10, 13 - parsedStartTime.length()); } else { startTime = Long.parseLong(parsedStartTime); } } catch (NumberFormatException nfe) { startTime = 0; } overallTDI.setStartTime((new Date(startTime)).toString()); } else { overallTDI.setStartTime(parsedStartTime); } parsedStartTime = null; } } dumpKey = overallTDI.getName(); } else if(!isPatternError() && (getRegexPattern() != null)) { try { Matcher m = getRegexPattern().matcher(line); if(m.matches()) { matched = m; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error during parsing line for timestamp regular expression!\n" + "Please check regular expression in your preferences. Deactivating\n" + "parsing for the rest of the file! Error Message is " + ex.getMessage() + " \n", "Error during Parsing", JOptionPane.ERROR_MESSAGE); //System.out.println("Failed parsing! " + ex.getMessage()); //ex.printStackTrace(); setPatternError(true); } } } else { if(line.startsWith("\"")) { if(title != null) { threads.put(title, content.toString()); content.append("</pre></pre>"); addToCategory(catThreads, title, null, content, singleLineCounter); threadCount++; } if(wContent != null) { wContent.append("</b><hr>"); addToCategory(catWaiting, title, wContent, content, singleLineCounter); wContent = null; waiting++; } if(sContent != null) { sContent.append("</b><hr>"); addToCategory(catSleeping, title, sContent, content, singleLineCounter); sContent = null; sleeping++; } if(lContent != null) { lContent.append("</b><hr>"); addToCategory(catLocking, title, lContent, content, singleLineCounter); lContent = null; locking++; } singleLineCounter = 0; while(!monitorStack.empty()) { mmap.parseAndAddThread((String)monitorStack.pop(), title, content.toString()); } title = line; content = new StringBuffer("<body bgcolor=\"ffffff\"><pre><font size=" + TDA.getFontSizeModifier(-1) + ">"); content.append(line); content.append("\n"); } else if (line.indexOf("at ") >= 0) { content.append(line); content.append("\n"); } else if (line.indexOf("java.lang.Thread.State") >= 0) { content.append(line); content.append("\n"); } else if (line.indexOf("Locked ownable synchronizers:") >= 0) { content.append(line); content.append("\n"); } else if (line.indexOf("- waiting on") >= 0) { String newLine = linkifyMonitor(line); content.append(newLine); if(sContent == null) { sContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } sContent.append(newLine); monitorStack.push(line); sContent.append("\n"); content.append("\n"); } else if (line.indexOf("- waiting to") >= 0) { String newLine = linkifyMonitor(line); content.append(newLine); if(wContent == null) { wContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } wContent.append(newLine); monitorStack.push(line); wContent.append("\n"); content.append("\n"); } else if (line.indexOf("- locked <") >= 0) { String newLine = linkifyMonitor(line); content.append(newLine); if(lContent == null) { lContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } lContent.append(newLine); monitorStack.push(line); lContent.append("\n"); content.append("\n"); } else if (line.indexOf("- ") >= 0) { content.append(line); content.append("\n"); } // last thread reached? if((line.indexOf("\"Suspend Checker Thread\"") >= 0) || (line.indexOf("\"VM Periodic Task Thread\"") >= 0) || (line.indexOf("<EndOfDump>") >= 0)) { finished = true; getBis().mark(getMarkSize()); if((checkForDeadlocks(threadDump)) == 0) { // no deadlocks found, set back original position. getBis().reset(); } getBis().mark(getMarkSize()); if(!(foundClassHistograms = checkForClassHistogram(threadDump))) { getBis().reset(); } } } } // last thread if(title != null) { threads.put(title, content.toString()); content.append("</pre></pre>"); addToCategory(catThreads, title, null, content, singleLineCounter); threadCount++; } if(wContent != null) { wContent.append("</b><hr>"); addToCategory(catWaiting, title, null, wContent, singleLineCounter); wContent = null; waiting++; } if(sContent != null) { sContent.append("</b><hr>"); addToCategory(catSleeping, title, sContent, content, singleLineCounter); sContent = null; sleeping++; } if(lContent != null) { lContent.append("</b><hr>"); addToCategory(catLocking, title, null, lContent, singleLineCounter); lContent = null; locking++; } int monitorCount = mmap.size(); int monitorsWithoutLocksCount = 0; // dump monitors if(mmap.size() > 0) { int[] result = dumpMonitors(catMonitors, catMonitorsLocks, mmap); monitorsWithoutLocksCount = result[0]; overallTDI.setOverallThreadsWaitingWithoutLocksCount(result[1]); } // display nodes with stuff to display if(waiting > 0) { overallTDI.setWaitingThreads((Category) catWaiting.getUserObject()); threadDump.add(catWaiting); } if(sleeping > 0) { overallTDI.setSleepingThreads((Category) catSleeping.getUserObject()); threadDump.add(catSleeping); } if(locking > 0) { overallTDI.setLockingThreads((Category) catLocking.getUserObject()); threadDump.add(catLocking); } if(monitorCount > 0) { overallTDI.setMonitors((Category) catMonitors.getUserObject()); threadDump.add(catMonitors); } if(monitorsWithoutLocksCount > 0) { overallTDI.setMonitorsWithoutLocks((Category) catMonitorsLocks.getUserObject()); threadDump.add(catMonitorsLocks); } overallTDI.setThreads((Category) catThreads.getUserObject()); ((Category) catThreads.getUserObject()).setName(((Category) catThreads.getUserObject()) + " (" + threadCount + " Threads overall)"); ((Category) catWaiting.getUserObject()).setName(((Category) catWaiting.getUserObject()) + " (" + waiting + " Threads waiting)"); ((Category) catSleeping.getUserObject()).setName(((Category) catSleeping.getUserObject()) + " (" + sleeping + " Threads sleeping)"); ((Category) catLocking.getUserObject()).setName(((Category) catLocking.getUserObject()) + " (" + locking + " Threads locking)"); ((Category) catMonitors.getUserObject()).setName(((Category) catMonitors.getUserObject()) + " (" + monitorCount + " Monitors)"); ((Category) catMonitorsLocks.getUserObject()).setName(((Category) catMonitorsLocks.getUserObject()) + " (" + monitorsWithoutLocksCount + " Monitors)"); // add thread dump to passed dump store. if((threadCount > 0) && (dumpKey != null)) { threadStore.put(dumpKey.trim(), threads); } return(threadCount > 0? threadDump : null); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return(null); } /** * add a monitor link for monitor navigation * @param line containing monitor */ private String linkifyMonitor(String line) { if(line != null && line.indexOf('<') >= 0) { String begin = line.substring(0, line.indexOf('<')); String monitor = line.substring(line.indexOf('<'), line.indexOf('>') + 1); String end = line.substring(line.indexOf('>') + 1); monitor = monitor.replaceAll("<", "<a href=\"monitor://" + monitor + "\">&lt;"); monitor = monitor.substring(0, monitor.length() - 1) + "&gt;</a>"; return(begin + monitor + end); } else { return(line); } } /** * add a monitor link for monitor navigation * @param line containing monitor */ private String linkifyDeadlockInfo(String line) { if(line != null && line.indexOf("Ox") >= 0) { String begin = line.substring(0, line.indexOf("0x")); int objectBegin = line.lastIndexOf("0x"); int monitorBegin = line.indexOf("0x"); String monitorHex = line.substring(monitorBegin, monitorBegin + 10); String monitor = line.substring(objectBegin, objectBegin + 10); String end = line.substring(line.indexOf("0x") + 10); monitor = "<a href=\"monitor://<" + monitor + ">\">" + monitorHex + "</a>"; return(begin + monitor + end); } else { return(line); } } /** * checks for the next class histogram and adds it to the tree node passed * @param threadDump which tree node to add the histogram. */ private boolean checkForClassHistogram(DefaultMutableTreeNode threadDump) throws IOException { HistogramTableModel classHistogram = parseNextClassHistogram(getBis()); if(classHistogram.getRowCount() > 0) { addHistogramToDump(threadDump, classHistogram); } return(classHistogram.getRowCount() > 0); } private void addHistogramToDump(DefaultMutableTreeNode threadDump, HistogramTableModel classHistogram) { DefaultMutableTreeNode catHistogram; HistogramInfo hi = new HistogramInfo("Class Histogram of Dump", classHistogram); catHistogram = new DefaultMutableTreeNode(hi); threadDump.add(catHistogram); } /** * parses the next class histogram found in the stream, uses the max check lines option to check * how many lines to parse in advance. * @param bis the stream to read. */ private HistogramTableModel parseNextClassHistogram(BufferedReader bis) throws IOException { boolean finished = false; boolean found = false; HistogramTableModel classHistogram = new HistogramTableModel(); int maxLinesCounter = 0; while(bis.ready() && !finished) { String line = bis.readLine().trim(); if(!found && !line.equals("")) { if (line.startsWith("num #instances #bytes class name")) { found = true; } else if(maxLinesCounter >= getMaxCheckLines()) { finished = true; } else { maxLinesCounter++; } } else if(found) { if(line.startsWith("Total ")) { // split string. String newLine = line.replaceAll("(\\s)+", ";"); String[] elems = newLine.split(";"); classHistogram.setBytes(Long.parseLong(elems[2])); classHistogram.setInstances(Long.parseLong(elems[1])); finished = true; } else if(!line.startsWith(" // removed blank, breaks splitting using blank... String newLine = line.replaceAll("<no name>", "<no-name>"); // split string. newLine = newLine.replaceAll("(\\s)+", ";"); String[] elems = newLine.split(";"); if(elems.length == 4) { classHistogram.addEntry(elems[3].trim(),Integer.parseInt(elems[2].trim()), Integer.parseInt(elems[1].trim())); } else { classHistogram.setIncomplete(true); finished = true; } } } } return(classHistogram); } /** * check if any dead lock information is logged in the stream * @param threadDump which tree node to add the histogram. */ private int checkForDeadlocks(DefaultMutableTreeNode threadDump) throws IOException { boolean finished = false; boolean found = false; int deadlocks = 0; int lineCounter = 0; StringBuffer dContent = new StringBuffer(); TreeCategory deadlockCat = new TreeCategory("Deadlocks", IconFactory.DEADLOCKS); DefaultMutableTreeNode catDeadlocks = new DefaultMutableTreeNode(deadlockCat); boolean first = true; while(getBis().ready() && !finished) { String line = getBis().readLine(); if(!found && !line.equals("")) { if (line.trim().startsWith("Found one Java-level deadlock")) { found = true; dContent.append("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); dContent.append("Found one Java-level deadlock"); dContent.append("</b><hr></font><pre>\n"); } else if(lineCounter >= getMaxCheckLines()) { finished = true; } else { lineCounter++; } } else if(found) { if(line.startsWith("Found one Java-level deadlock")) { if(dContent.length() > 0) { deadlocks++; addToCategory(catDeadlocks, "Deadlock No. " + (deadlocks), null, dContent, 0); } dContent = new StringBuffer(); dContent.append("</pre><b><font size=" + TDA.getFontSizeModifier(-1) + ">"); dContent.append("Found one Java-level deadlock"); dContent.append("</b><hr></font><pre>\n"); first = true; } else if((line.indexOf("Found") >= 0) && (line.endsWith("deadlocks.") || line.endsWith("deadlock."))) { finished = true; } else if(line.startsWith("=======")) { // ignore this line } else if(line.indexOf(" monitor 0x") >= 0) { dContent.append(linkifyDeadlockInfo(line)); dContent.append("\n"); } else if(line.indexOf("Java stack information for the threads listed above") >= 0) { dContent.append("</pre><br><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); dContent.append("Java stack information for the threads listed above"); dContent.append("</b><hr></font><pre>"); first = true; } else if ((line.indexOf("- waiting on") >= 0) || (line.indexOf("- waiting to") >= 0) || (line.indexOf("- locked") >= 0)) { dContent.append(linkifyMonitor(line)); dContent.append("\n"); } else if(line.trim().startsWith("\"")) { dContent.append("</pre>"); if(first) { first = false; } else { dContent.append("<br>"); } dContent.append("<b><font size=" + TDA.getFontSizeModifier(-1) + "><code>"); dContent.append(line); dContent.append("</font></code></b><pre>"); } else { dContent.append(line); dContent.append("\n"); } } } if(dContent.length() > 0) { deadlocks++; addToCategory(catDeadlocks, "Deadlock No. " + (deadlocks), null, dContent, 0); } if(deadlocks > 0) { threadDump.add(catDeadlocks); ((ThreadDumpInfo) threadDump.getUserObject()).setDeadlocks((TreeCategory) catDeadlocks.getUserObject()); deadlockCat.setName("Deadlocks (" + deadlocks + (deadlocks == 1 ? " deadlock)" : " deadlocks)")); } return(deadlocks); } /** * dump the monitor information * @param catMonitors * @param catMonitorsLocks * @param mmap * @return */ private int[] dumpMonitors(DefaultMutableTreeNode catMonitors, DefaultMutableTreeNode catMonitorsLocks, MonitorMap mmap) { Iterator iter = mmap.iterOfKeys(); int monitorsWithoutLocksCount = 0; int overallThreadsWaiting = 0; while(iter.hasNext()) { String monitor = (String) iter.next(); Map[] threads = mmap.getFromMonitorMap(monitor); ThreadInfo mi = new ThreadInfo(monitor, null, "", 0, null); DefaultMutableTreeNode monitorNode = new DefaultMutableTreeNode(mi); // first the locks Iterator iterLocks = threads[0].keySet().iterator(); int locks = 0; int sleeps = 0; int waits = 0; while(iterLocks.hasNext()) { String thread = (String) iterLocks.next(); if(threads[2].containsKey(thread)) { createNode(monitorNode, "locks and sleeps on monitor: " + thread, null, (String) threads[0].get(thread), 0); sleeps++; } else if(threads[1].containsKey(thread)) { createNode(monitorNode, "locks and waits on monitor: " + thread, null, (String) threads[0].get(thread), 0); sleeps++; } else { createNode(monitorNode, "locked by " + thread, null, (String) threads[0].get(thread), 0); } locks++; } Iterator iterWaits = threads[1].keySet().iterator(); while(iterWaits.hasNext()) { String thread = (String) iterWaits.next(); if(!threads[0].containsKey(thread)) { createNode(monitorNode, "waits on monitor: " + thread, null, (String) threads[1].get(thread), 0); waits++; } } mi.setContent(ThreadDumpInfo.getMonitorInfo(locks, waits, sleeps)); mi.setName(mi.getName() + ": " + (sleeps) + " Thread(s) sleeping, " + (waits) + " Thread(s) waiting, " + (locks) + " Thread(s) locking"); ((Category)catMonitors.getUserObject()).addToCatNodes(monitorNode); if(locks == 0) { monitorsWithoutLocksCount++; overallThreadsWaiting+=waits; ((Category)catMonitorsLocks.getUserObject()).addToCatNodes(monitorNode); } } return new int[]{monitorsWithoutLocksCount, overallThreadsWaiting}; } /** * parses a loggc file stream and reads any found class histograms and adds the to the dump store * @param loggcFileStream the stream to read * @param root the root node of the dumps. */ public void parseLoggcFile(InputStream loggcFileStream, DefaultMutableTreeNode root) { BufferedReader bis = new BufferedReader(new InputStreamReader(loggcFileStream)); Vector histograms = new Vector(); try { while(bis.ready()) { bis.mark(getMarkSize()); String nextLine = bis.readLine(); if(nextLine.startsWith("num #instances #bytes class name")) { bis.reset(); histograms.add(parseNextClassHistogram(bis)); } } // now add the found histograms to the tree. for(int i = histograms.size()-1; i >= 0; i DefaultMutableTreeNode dump = getNextDumpForHistogram(root); if(dump != null) { addHistogramToDump(dump, (HistogramTableModel) histograms.get(i)); } } } catch (IOException ex) { ex.printStackTrace(); } } /** * generate thread info token for table view. * @param name the thread info. * @return thread tokens. */ public String[] getThreadTokens(String name) { String[] tokens = null; if(name.indexOf("prio") > 0) { tokens = new String[7]; tokens[0] = name.substring(1, name.lastIndexOf('"')); tokens[1] = name.indexOf("daemon") > 0 ? "Daemon" : "Task"; tokens[2] = name.substring(name.indexOf("prio=") + 5, name.indexOf("tid=") - 1); tokens[3] = String.valueOf(Integer.parseInt(name.substring(name.indexOf("tid=") + 6, name.indexOf("nid=") - 1), 16)); tokens[4] = String.valueOf(Integer.parseInt(name.substring(name.indexOf("nid=") + 6, name.indexOf(" ", name.indexOf("nid="))), 16)); if (name.indexOf('[') > 0) { tokens[5] = name.substring(name.indexOf(" ", name.indexOf("nid=")) + 1, name.indexOf('[', name.indexOf("nid=")) - 1); tokens[6] = name.substring(name.indexOf('[')); } else { tokens[5] = name.substring(name.indexOf(" ", name.indexOf("nid=")) + 1); tokens[6] = "<no address range>"; } } else { tokens = new String[3]; tokens[0] = name.substring(1, name.lastIndexOf('"')); if(name.indexOf("nid=") > 0) { tokens[1] = name.substring(name.indexOf("nid=") + 4, name.indexOf("state=") - 1); tokens[2] = name.substring(name.indexOf("state=") +6); } else { tokens[1] = name.substring(name.indexOf("id=") + 3, name.indexOf(" in")); tokens[2] = name.substring(name.indexOf(" in") +3); } } return (tokens); } /** * check if the passed logline contains the beginning of a sun jdk thread * dump. * @param logLine the line of the logfile to test * @return true, if the start of a sun thread dump is detected. */ public static boolean checkForSupportedThreadDump(String logLine) { return (logLine.trim().indexOf("Full thread dump Java HotSpot(TM)") >= 0); } }
package ua.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; public class PointTests { @Test public void testDistanceCorrectOne(){ Point p11 = new Point(3, 4); Point p22 = new Point(7, 8); Assert.assertEquals(p11.distance(p11, p22), 5.656854249492381); } @Test public void testDistanceCorrectTwo(){ Point p11 = new Point(3, 4); Point p22 = new Point(5, 6); Assert.assertEquals(p11.distance(p11, p22), 2.8284271247461903); } @Test public void testDistanceFalse(){ Point p11 = new Point(3, 4); Point p22 = new Point(5, 6); Assert.assertEquals(p11.distance(p11, p22), 22.0); } }
package beaform.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import javax.transaction.NotSupportedException; import javax.transaction.SystemException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import beaform.entities.Formula; import beaform.entities.FormulaTag; import beaform.entities.Ingredient; /** * This class handles all DB access for formulas. * * @author Steven Post * */ public final class FormulaDAO { private static final Logger LOG = LoggerFactory.getLogger(FormulaDAO.class); /** Query to search for a formula by tag */ private static final String FORMULA_BY_TAG = "MATCH (t:FormulaTag { name:{name} })<-[r]-(f:Formula) RETURN f"; private FormulaDAO() { // private constructor, because this is a utility class. } public static List<Ingredient> getIngredients(final Formula formula) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); entityManager.getTransaction().begin(); final Formula retrievedFormula = entityManager.find(Formula.class, formula.getName()); final List<Ingredient> retList = retrievedFormula.getIngredients(); entityManager.getTransaction().commit(); entityManager.clear(); return retList; } public static void updateExisting(final String name, final String description, final String totalAmount, final List<Ingredient> ingredients, final List<FormulaTag> tags) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); entityManager.getTransaction().begin(); final Formula formula = entityManager.find(Formula.class, name); setFormulaProperties(formula, description, totalAmount); clearFormulaRelations(formula); addTags(tags, formula); addIngredientsToFormula(formula, ingredients); entityManager.getTransaction().commit(); entityManager.detach(formula); } private static void addIngredientsToFormula(final Formula formula, final List<Ingredient> ingredients) { for (final Ingredient ingredient : ingredients) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); final Formula dbVersion = entityManager.find(Formula.class, ingredient.getFormula().getName()); final Formula toAdd; if (dbVersion != null) { toAdd = dbVersion; } else { toAdd = ingredient.getFormula(); } formula.addIngredient(toAdd, ingredient.getAmount()); } } public static void addFormula(final String name, final String description, final String totalAmount, final List<Ingredient> ingredients, final List<FormulaTag> tags) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); entityManager.getTransaction().begin(); final Formula formula = new Formula(name, description, totalAmount); addTags(tags, formula); addIngredientsToFormula(formula, ingredients); entityManager.persist(formula); entityManager.getTransaction().commit(); entityManager.detach(formula); entityManager.clear(); } private static void setFormulaProperties(final Formula formula, final String description, final String totalAmount) { formula.setDescription(description); formula.setTotalAmount(totalAmount); } /** * This method adds tags to a formula. * It assumes a running transaction. * * @param tags A list of tags * @param entityManager an open entity manager * @param formula the formula to add the tags to * @throws NotSupportedException If the calling thread is already * associated with a transaction, * and nested transactions are not supported. * @throws SystemException If the transaction service fails in an unexpected way. */ private static void addTags(final List<FormulaTag> tags, final Formula formula) { for (final FormulaTag tag : tags) { addTagToFormula(formula, tag); } } private static void addTagToFormula(final Formula formula, final FormulaTag tag) { // See if the tag exist in the DB, if so, use it. FormulaTag tagToAdd; try { tagToAdd = FormulaTagDAO.findByObject(tag); } catch (NoResultException e1) { if (LOG.isTraceEnabled()) { LOG.trace("No tag with name " + tag.getName() + " found: " + e1.getMessage(), e1); } tagToAdd = tag; } formula.addTag(tagToAdd); } /** * This method finds a formula in the DB based on a name. * It assumes a transaction is already in progress. * * @param name the name of the formula to look for * @return the found {@link Formula} or null if none was found. */ public static Formula findFormulaByName(final String name) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); entityManager.getTransaction().begin(); final Formula result = entityManager.find(Formula.class, name); if (LOG.isDebugEnabled()) { LOG.debug("Found: " + result); } entityManager.getTransaction().commit(); if (result != null) { entityManager.detach(result); } return result; } public static List<Formula> findFormulasByTag(final String tagName) { final EntityManager entityManager = GraphDbHandler.getInstance().getEntityManager(); entityManager.getTransaction().begin(); final List<Formula> result = findByTag(tagName, entityManager); if (LOG.isDebugEnabled()) { LOG.debug("Found: " + result); } entityManager.getTransaction().commit(); for (final Formula formula : result) { entityManager.detach(formula); } return result; } private static List<Formula> findByTag(final String tagName, final EntityManager entityManager) { final Query query = entityManager.createNativeQuery(FORMULA_BY_TAG, Formula.class); query.setParameter("name", tagName); return query.getResultList(); } private static void clearFormulaRelations(final Formula formula) { formula.deleteAllIngredients(); formula.deleteAllTags(); } }
package org.hbase.async; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import org.jboss.netty.buffer.ChannelBuffer; import org.hbase.async.generated.ClientPB.Action; import org.hbase.async.generated.ClientPB.MultiRequest; import org.hbase.async.generated.ClientPB.MultiResponse; import org.hbase.async.generated.ClientPB.MutationProto; import org.hbase.async.generated.ClientPB.RegionAction; import org.hbase.async.generated.ClientPB.RegionActionResult; import org.hbase.async.generated.ClientPB.Result; import org.hbase.async.generated.ClientPB.ResultOrException; import org.hbase.async.generated.HBasePB.NameBytesPair; /** * Package-private class to batch multiple RPCs for a same region together. * <p> * This RPC is guaranteed to be sent atomically (but HBase doesn't guarantee * that it will apply it atomically). */ final class MultiAction extends HBaseRpc implements HBaseRpc.IsEdit { // NOTE: I apologize for the long methods and complex control flow logic, // with many nested loops and `if's. `multiPut' and `multi' have always // been a gigantic mess in HBase, and despite my best efforts to provide // a reasonable implementation, it's obvious that the resulting code is // unwieldy. I originally wrote support for `multi' as a separate class // from `multiPut', but this resulted in a lot of code duplication and // added complexity in other places that had to deal with either kind of // RPCs depending on the server version. Hence this class supports both // RPCs, which does add a bit of complexity to the already unnecessarily // complex logic. This was better than all the code duplication. And // believe me, what's here is -- in my biased opinion -- significantly // better than the insane spaghetti mess in HBase's client and server. /** RPC method name for HBase before 0.92. */ private static final byte[] MULTI_PUT = { 'm', 'u', 'l', 't', 'i', 'P', 'u', 't' }; /** RPC method name for HBase 0.92 to 0.94. */ private static final byte[] MULTI = { 'm', 'u', 'l', 't', 'i' }; /** RPC method name for HBase 0.95 and above. */ private static final byte[] MMULTI = { 'M', 'u', 'l', 't', 'i' }; /** Template for NSREs. */ private static final NotServingRegionException NSRE = new NotServingRegionException("Region unavailable", null); /** * Protocol version from which we can use `multi' instead of `multiPut'. * Technically we could use `multi' with HBase 0.90.x, but as explained * in HBASE-5204, because of a change in HBASE-3335 this is harder than * necessary, so we don't support it. */ static final byte USE_MULTI = RegionClient.SERVER_VERSION_092_OR_ABOVE; /** * All the RPCs in this batch. * We'll sort this list before serializing it. * @see MultiActionComparator */ private final ArrayList<BatchableRpc> batch = new ArrayList<BatchableRpc>(); @Override byte[] method(final byte server_version) { if (server_version >= RegionClient.SERVER_VERSION_095_OR_ABOVE) { return MMULTI; } return server_version >= USE_MULTI ? MULTI : MULTI_PUT; } /** Returns the number of RPCs in this batch. */ public int size() { return batch.size(); } /** * Adds an RPC to this batch. * <p> * @param rpc The RPC to add in this batch. * Any edit added <b>must not</b> specify an explicit row lock. */ public void add(final BatchableRpc rpc) { if (rpc.lockid != RowLock.NO_LOCK) { throw new AssertionError("Should never happen! We don't do multi-put" + " with RowLocks but we've been given an edit that has one!" + " edit=" + rpc + ", this=" + this); } batch.add(rpc); } /** Returns the list of individual RPCs that make up this batch. */ ArrayList<BatchableRpc> batch() { return batch; } /** * Predicts a lower bound on the serialized size of this RPC. * This is to avoid using a dynamic buffer, to avoid re-sizing the buffer. * Since we use a static buffer, if the prediction is wrong and turns out * to be less than what we need, there will be an exception which will * prevent the RPC from being serialized. That'd be a severe bug. * @param server_version What RPC protocol version the server is running. */ private int predictSerializedSize(final byte server_version) { // See the comment in serialize() about the for loop that follows. int size = 0; size += 4; // int: Number of parameters. size += 1; // byte: Type of the 1st parameter. size += 1; // byte: Type again (see HBASE-2877). size += 4; // int: How many regions do we want to affect? // Are we serializing a `multi' RPC, or `multiPut'? final boolean use_multi = method(server_version) == MULTI; BatchableRpc prev = PutRequest.EMPTY_PUT; for (final BatchableRpc rpc : batch) { final byte[] region_name = rpc.getRegion().name(); final boolean new_region = !Bytes.equals(prev.getRegion().name(), region_name); final byte[] family = rpc.family(); final boolean new_key = (new_region || prev.code() != rpc.code() || !Bytes.equals(prev.key, rpc.key) || family == DeleteRequest.WHOLE_ROW); final boolean new_family = new_key || !Bytes.equals(prev.family(), family); if (new_region) { size += 3; // vint: region name length (3 bytes => max length = 32768). size += region_name.length; // The region name. size += 4; // int: How many RPCs for this region. } final int key_length = rpc.key.length; if (new_key) { if (use_multi) { size += 4; // int: Number of "attributes" for the last key (none). size += 4; // Index of this `action'. size += 3; // 3 bytes to serialize `null'. size += 1; // byte: Type code for `Action'. size += 1; // byte: Type code again (see HBASE-2877). size += 1; // byte: Code for a `Row' object. size += 1; // byte: Code for a `Put' object. } size += 1; // byte: Version of Put. size += 3; // vint: row key length (3 bytes => max length = 32768). size += key_length; // The row key. size += 8; // long: Timestamp. size += 8; // long: Lock ID. size += 1; // bool: Whether or not to write to the WAL. size += 4; // int: Number of families for which we have edits. } if (new_family) { size += 1; // vint: Family length (guaranteed on 1 byte). size += family.length; // The family. size += 4; // int: Number of KeyValues that follow. if (rpc.code() == PutRequest.CODE) { size += 4; // int: Total number of bytes for all those KeyValues. } } size += rpc.payloadSize(); prev = rpc; } return size; } /** Serializes this request. */ ChannelBuffer serialize(final byte server_version) { if (server_version < RegionClient.SERVER_VERSION_095_OR_ABOVE) { return serializeOld(server_version); } Collections.sort(batch, SORT_BY_REGION); final MultiRequest.Builder req = MultiRequest.newBuilder(); RegionAction.Builder actions = null; byte[] prev_region = HBaseClient.EMPTY_ARRAY; int i = 0; for (final BatchableRpc rpc : batch) { final RegionInfo region = rpc.getRegion(); final boolean new_region = !Bytes.equals(prev_region, region.name()); if (new_region) { if (actions != null) { // If not the first iteration ... req.addRegionAction(actions.build()); // ... push actions thus far. } actions = RegionAction.newBuilder(); actions.setRegion(rpc.getRegion().toProtobuf()); prev_region = region.name(); } final Action action = Action.newBuilder() .setIndex(i++) .setMutation(rpc.toMutationProto()) .build(); actions.addAction(action); } req.addRegionAction(actions.build()); return toChannelBuffer(MMULTI, req.build()); } /** Serializes this request for HBase 0.94 and before. */ private ChannelBuffer serializeOld(final byte server_version) { // Due to the wire format expected by HBase, we need to group all the // edits by region, then by key, then by family. HBase does this by // building a crazy map-of-map-of-map-of-list-of-edits, but this is // memory and time inefficient (lots of unnecessary references and // O(n log n) operations). The approach we take here is to sort the // list and iterate on it. Each time we find a different family or // row key or region, we start a new set of edits. Because the RPC // format needs to know the number of edits or bytes that follows in // various places, we store a "0" value and then later monkey-patch it // once we cross a row key / family / region boundary, because we can't // efficiently tell ahead of time how many edits or bytes will follow // until we cross such boundaries. Collections.sort(batch, MULTI_CMP); final ChannelBuffer buf = newBuffer(server_version, predictSerializedSize(server_version)); buf.writeInt(1); // Number of parameters. // Are we serializing a `multi' RPC, or `multiPut'? final boolean use_multi = method(server_version) == MULTI; { // 1st and only param. final int code = use_multi ? 66 : 57; // `MultiAction' or `MultiPut'. buf.writeByte(code); // Type code for the parameter. buf.writeByte(code); // Type code again (see HBASE-2877). } buf.writeInt(0); // How many regions do we want to affect? int nregions = 0; int nkeys_index = -1; int nkeys = 0; int nfamilies_index = -1; int nfamilies = 0; int nkeys_per_family_index = -1; int nkeys_per_family = 0; int nbytes_per_family = 0; int nrpcs_per_key = 0; BatchableRpc prev = PutRequest.EMPTY_PUT; for (final BatchableRpc rpc : batch) { final byte[] region_name = rpc.getRegion().name(); final boolean new_region = !Bytes.equals(prev.getRegion().name(), region_name); final byte[] family = rpc.family(); final boolean new_key = (new_region || prev.code() != rpc.code() || !Bytes.equals(prev.key, rpc.key) || family == DeleteRequest.WHOLE_ROW); final boolean new_family = new_key || !Bytes.equals(prev.family(), family); if (new_key && use_multi && nkeys_index > 0) { buf.writeInt(0); // Number of "attributes" for the last key (none). // Trailing useless junk from `Action'. After serializing its // `action' (which implements an interface awesomely named `Row'), // HBase adds the index of the `action' as the server will sort // actions by key. This is pretty useless as if the client was // sorting things before sending them off to the server, like we // do, then we wouldn't need to pass an index to be able to match // up requests and responses. Since we don't need this index, we // instead use this field for another purpose: remembering how // many RPCs we sent for this particular key. This will help us // when de-serializing the response. buf.writeInt(nrpcs_per_key); nrpcs_per_key = 0; // Then, because an `Action' can also contain a result, the code // also serializes that. Of course for us end-users, this is stupid // because we never send a result along with our request. writeHBaseNull(buf); } if (new_region) { // Monkey-patch the number of edits of the previous region. if (nkeys_index > 0) { buf.setInt(nkeys_index, nkeys); nkeys = 0; } nregions++; writeByteArray(buf, region_name); // The region name. nkeys_index = buf.writerIndex(); // Number of keys for which we have RPCs for this region. buf.writeInt(0); // We'll monkey patch this later. } final byte[] key = rpc.key; if (new_key) { // Monkey-patch the number of families of the previous key. if (nfamilies_index > 0) { buf.setInt(nfamilies_index, nfamilies); nfamilies = 0; } if (use_multi) { // Serialize an `Action' for the RPCs on this row. buf.writeByte(65); // Code for an `Action' object. buf.writeByte(65); // Code again (see HBASE-2877). // Inside the action, serialize a `Put' object. buf.writeByte(64); // Code for a `Row' object. buf.writeByte(rpc.code()); // Code this object. } nkeys++; // Right now we only support batching puts. In the future this part // of the code will have to change to also want to allow get/deletes. // The follow serializes a `Put'. buf.writeByte(rpc.version(server_version)); // Undocumented versioning. writeByteArray(buf, key); // The row key. // This timestamp is unused, only the KeyValue-level timestamp is // used, except in one case: whole-row deletes. In that case only, // this timestamp is used by the RegionServer to create per-family // deletes for that row. See HRegion.prepareDelete() for more info. buf.writeLong(rpc.timestamp); // Timestamp. buf.writeLong(RowLock.NO_LOCK); // Lock ID. buf.writeByte(rpc.durable ? 0x01 : 0x00); // Use the WAL? nfamilies_index = buf.writerIndex(); // Number of families that follow. buf.writeInt(0); // We'll monkey patch this later. } if (new_family) { // Monkey-patch the number and size of edits for the previous family. if (nkeys_per_family_index > 0) { buf.setInt(nkeys_per_family_index, nkeys_per_family); if (prev.code() == PutRequest.CODE) { buf.setInt(nkeys_per_family_index + 4, nbytes_per_family); } nkeys_per_family_index = -1; nkeys_per_family = 0; nbytes_per_family = 0; } if (family == DeleteRequest.WHOLE_ROW) { prev = rpc; // Short circuit. We have no KeyValue to write. continue; // So loop again directly. } nfamilies++; writeByteArray(buf, family); // The column family. nkeys_per_family_index = buf.writerIndex(); // Number of "KeyValues" that follow. buf.writeInt(0); // We'll monkey patch this later. if (rpc.code() == PutRequest.CODE) { // Total number of bytes taken by those "KeyValues". // This is completely useless and only done for `Put'. buf.writeInt(0); // We'll monkey patch this later. } } nkeys_per_family += rpc.numKeyValues(); nrpcs_per_key++; nbytes_per_family += rpc.payloadSize(); rpc.serializePayload(buf); prev = rpc; } // Yay, we made it! if (use_multi) { buf.writeInt(0); // Number of "attributes" for the last key (none). // Trailing junk for the last `Action'. See comment above. buf.writeInt(nrpcs_per_key); writeHBaseNull(buf); // Useless. } // Note: the only case where nkeys_per_family_index remained -1 throughout // this whole ordeal is where we didn't have any KV to serialize because // every RPC was a `DeleteRequest.WHOLE_ROW'. if (nkeys_per_family_index > 0) { // Monkey-patch everything for the last set of edits. buf.setInt(nkeys_per_family_index, nkeys_per_family); if (prev.code() == PutRequest.CODE) { buf.setInt(nkeys_per_family_index + 4, nbytes_per_family); } } buf.setInt(nfamilies_index, nfamilies); buf.setInt(nkeys_index, nkeys); // Monkey-patch the number of regions affected by this RPC. int header_length = 4 + 4 + 2 + method(server_version).length; if (server_version >= RegionClient.SERVER_VERSION_092_OR_ABOVE) { header_length += 1 + 8 + 4; } buf.setInt(header_length + 4 + 1 + 1, nregions); return buf; } public String toString() { // Originally this was simply putting all the batch in the toString // representation, but that's way too expensive when we have large // batches. So instead we toString each RPC until we hit some // hard-coded upper bound on how much data we're willing to put into // the toString. If we have too many RPCs and hit that constant, // we skip all the remaining ones until the last one, as it's often // useful to see the last RPC added when debugging. final StringBuilder buf = new StringBuilder(); buf.append("MultiAction(batch=["); final int nrpcs = batch.size(); int i; for (i = 0; i < nrpcs; i++) { if (buf.length() >= 1024) { break; } buf.append(batch.get(i)).append(", "); } if (i < nrpcs) { if (i == nrpcs - 1) { buf.append("... 1 RPC not shown])"); } else { buf.append("... ").append(nrpcs - 1 - i) .append(" RPCs not shown ..., ") .append(batch.get(nrpcs - 1)) .append("])"); } } else { buf.setLength(buf.length() - 2); // Remove the last ", " buf.append("])"); } return buf.toString(); } /** * Sorts {@link BatchableRpc}s appropriately for the multi-put / multi-action RPC. * We sort by region, row key, column family. No ordering is needed on the * column qualifier or value. */ static final MultiActionComparator MULTI_CMP = new MultiActionComparator(); /** * Sorts {@link BatchableRpc}s appropriately for the `multi' RPC. * Used with HBase 0.94 and earlier only. */ private static final class MultiActionComparator implements Comparator<BatchableRpc> { private MultiActionComparator() { // Can't instantiate outside of this class. } @Override /** * Compares two RPCs. */ public int compare(final BatchableRpc a, final BatchableRpc b) { int d; if ((d = Bytes.memcmp(a.getRegion().name(), b.getRegion().name())) != 0) { return d; } else if ((d = a.code() - b.code()) != 0) { // Sort by code before key. // Note that DeleteRequest.code() < PutRequest.code() and this matters // as the RegionServer processes deletes before puts, and we want to // send RPCs in the same order as they will be processed. return d; } else if ((d = Bytes.memcmp(a.key, b.key)) != 0) { return d; } return Bytes.memcmp(a.family(), b.family()); } } /** * Sorts {@link BatchableRpc}s appropriately for HBase 0.95+ multi-action. */ static final RegionComparator SORT_BY_REGION = new RegionComparator(); /** * Sorts {@link BatchableRpc}s by region. * Used with HBase 0.95+ only. */ private static final class RegionComparator implements Comparator<BatchableRpc> { private RegionComparator() { // Can't instantiate outside of this class. } @Override /** Compares two RPCs. */ public int compare(final BatchableRpc a, final BatchableRpc b) { return Bytes.memcmp(a.getRegion().name(), b.getRegion().name()); } } @Override Object deserialize(final ChannelBuffer buf, final int cell_size) { HBaseRpc.ensureNoCell(cell_size); final MultiResponse resp = readProtobuf(buf, MultiResponse.PARSER); final int nrpcs = batch.size(); final Object[] resps = new Object[nrpcs]; int n = 0; // Index in `batch'. int r = 0; // Index in `regionActionResult' in the PB. while (n < nrpcs) { final RegionActionResult results = resp.getRegionActionResult(r++); final int nresults = results.getResultOrExceptionCount(); if (results.hasException()) { if (nresults != 0) { throw new InvalidResponseException("All edits in a batch failed yet" + " we found " + nresults + " results", results); } // All the edits for this region have failed, however the PB doesn't // tell us how many edits there were for that region, and we don't // keep track of this information except temporarily during // serialization. So we need to go back through our list again to // re-count how many we did put together in this batch, so we can fail // all those RPCs. int last_edit = n + 1; // +1 because we have at least 1 edit. final byte[] region_name = batch.get(n).getRegion().name(); while (last_edit < nrpcs && Bytes.equals(region_name, batch.get(last_edit).getRegion().name())) { last_edit++; } final NameBytesPair pair = results.getException(); for (int j = n; j < last_edit; j++) { resps[j] = RegionClient.decodeExceptionPair(batch.get(j), pair); } n = last_edit; continue; // This batch failed, move on. } // else: parse out the individual results: for (int j = 0; j < nresults; j++) { final ResultOrException roe = results.getResultOrException(j); final int index = roe.getIndex(); if (index != n) { throw new InvalidResponseException("Expected result + " but got result #" + index, results); } final Object result; if (roe.hasException()) { final NameBytesPair pair = roe.getException(); // This RPC failed, get what the exception was. result = RegionClient.decodeExceptionPair(batch.get(n), pair); } else { // We currently don't care what the result was: if it wasn't an // error, it was a success, period. For a put/delete the result // would be empty anyway. result = SUCCESS; } resps[n++] = result; } } if (n != nrpcs) { throw new InvalidResponseException("Expected " + nrpcs + " results but got " + n, resp); } return new Response(resps); } /** * Response to a {@link MultiAction} RPC. */ final class Response { /** Response for each Action that was in the batch, in the same order. */ private final Object[] resps; /** Constructor. */ Response(final Object[] resps) { assert resps.length == batch.size() : "Got " + resps.length + " responses but expected " + batch.size(); this.resps = resps; } /** * Returns the result number #i embodied in this response. * @throws IndexOutOfBoundsException if i is greater than batch.size() */ public Object result(final int i) { return resps[i]; } public String toString() { return "MultiAction.Response(" + Arrays.toString(resps) + ')'; } } /** * De-serializes the response to a {@link MultiAction} RPC. * See HBase's {@code MultiResponse}. * Only used with HBase 0.94 and earlier. */ Response responseFromBuffer(final ChannelBuffer buf) { switch (buf.readByte()) { case 58: return deserializeMultiPutResponse(buf); case 67: return deserializeMultiResponse(buf); } throw new NonRecoverableException("Couldn't de-serialize " + Bytes.pretty(buf)); } /** * De-serializes a {@code MultiResponse}. * This is only used when talking to HBase 0.92.x to 0.94.x. */ Response deserializeMultiResponse(final ChannelBuffer buf) { final int nregions = buf.readInt(); HBaseRpc.checkNonEmptyArrayLength(buf, nregions); final Object[] resps = new Object[batch.size()]; int n = 0; // Index in `batch'. for (int i = 0; i < nregions; i++) { final byte[] region_name = HBaseRpc.readByteArray(buf); final int nkeys = buf.readInt(); HBaseRpc.checkNonEmptyArrayLength(buf, nkeys); for (int j = 0; j < nkeys; j++) { final int nrpcs_per_key = buf.readInt(); boolean error = buf.readByte() != 0x00; Object resp; // Response for the current region. if (error) { final HBaseException e = RegionClient.deserializeException(buf, null); resp = e; } else { resp = RegionClient.deserializeObject(buf, this); // A successful response to a `Put' will be an empty `Result' // object, which we de-serialize as an empty `ArrayList'. // There's no need to waste memory keeping these around. if (resp instanceof ArrayList && ((ArrayList) resp).isEmpty()) { resp = SUCCESS; } else if (resp == null) { // Awesomely, `null' is used to indicate all RPCs for this region // have failed, and we're not told why. Most of the time, it will // be an NSRE, so assume that. What were they thinking when they // wrote that code in HBase? Seriously WTF. resp = NSRE; error = true; } } if (error) { final HBaseException e = (HBaseException) resp; for (int k = 0; k < nrpcs_per_key; k++) { // We need to "clone" the exception for each RPC, as each RPC that // failed needs to have its own exception with a reference to the // failed RPC. This makes significantly simplifies the callbacks // that do error handling, as they can extract the RPC out of the // exception. The downside is that we don't have a perfect way of // cloning "e", so instead we just abuse its `make' factory method // slightly to duplicate it. This mangles the message a bit, but // that's mostly harmless. resps[n + k] = e.make(e.getMessage(), batch.get(n + k)); } } else { for (int k = 0; k < nrpcs_per_key; k++) { resps[n + k] = resp; } } n += nrpcs_per_key; } } return new Response(resps); } /** * De-serializes a {@code MultiPutResponse}. * This is only used when talking to old versions of HBase (pre 0.92). */ Response deserializeMultiPutResponse(final ChannelBuffer buf) { final int nregions = buf.readInt(); HBaseRpc.checkNonEmptyArrayLength(buf, nregions); final int nrpcs = batch.size(); final Object[] resps = new Object[nrpcs]; int n = 0; // Index in `batch'. for (int i = 0; i < nregions; i++) { final byte[] region_name = HBaseRpc.readByteArray(buf); // Sanity check. Response should give us regions back in same order. assert Bytes.equals(region_name, batch.get(n).getRegion().name()) : ("WTF? " + Bytes.pretty(region_name) + " != " + batch.get(n).getRegion().name()); final int failed = buf.readInt(); // Index of the first failed edit. // Because of HBASE-2898, we don't know which RPCs exactly failed. We // only now that for that region, the one at index `failed' wasn't // successful, so we can only assume that the subsequent ones weren't // either, and retry them. First we need to find out how many RPCs // we originally had for this region. int edits_per_region = n; while (edits_per_region < nrpcs && Bytes.equals(region_name, batch.get(edits_per_region).getRegion().name())) { edits_per_region++; } edits_per_region -= n; assert failed < edits_per_region : "WTF? Found more failed RPCs " + failed + " than sent " + edits_per_region + " to " + Bytes.pretty(region_name); // If `failed == -1' then we now that nothing has failed. Otherwise, we // have that RPCs in [n; n + failed - 1] have succeeded, and RPCs in // [n + failed; n + edits_per_region] have failed. if (failed == -1) { // Fast-path for the case with no failures. for (int j = 0; j < edits_per_region; j++) { resps[n + j] = SUCCESS; } } else { // We had some failures. assert failed >= 0 : "WTF? Found a negative failure index " + failed + " for region " + Bytes.pretty(region_name); for (int j = 0; j < failed; j++) { resps[n + j] = SUCCESS; } final String msg = "Multi-put failed on RPC #" + failed + "/" + edits_per_region + " on region " + Bytes.pretty(region_name); for (int j = failed; j < edits_per_region; j++) { resps[n + j] = new MultiPutFailedException(msg, batch.get(n + j)); } } n += edits_per_region; } return new Response(resps); } /** * Used to represent the partial failure of a multi-put exception. * This is only used with older versions of HBase (pre 0.92). */ private final class MultiPutFailedException extends RecoverableException implements HasFailedRpcException { final HBaseRpc failed_rpc; /** * Constructor. * @param msg The message of the exception. * @param failed_rpc The RPC that caused this exception. */ MultiPutFailedException(final String msg, final HBaseRpc failed_rpc) { super(msg); this.failed_rpc = failed_rpc; } @Override public String getMessage() { return super.getMessage() + "\nCaused by RPC: " + failed_rpc; } public HBaseRpc getFailedRpc() { return failed_rpc; } @Override MultiPutFailedException make(final Object msg, final HBaseRpc rpc) { return new MultiPutFailedException(msg.toString(), rpc); } private static final long serialVersionUID = 1326900942; } /** Singleton class returned to indicate success of a multi-put. */ private static final class MultiActionSuccess { private MultiActionSuccess() { } public String toString() { return "MultiActionSuccess"; } } private static final MultiActionSuccess SUCCESS = new MultiActionSuccess(); }
package io.grpc.benchmarks; import static java.util.concurrent.ForkJoinPool.defaultForkJoinWorkerThreadFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.UncaughtExceptionHandlers; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.Status; import io.grpc.benchmarks.proto.Messages; import io.grpc.benchmarks.proto.Messages.Payload; import io.grpc.benchmarks.proto.Messages.SimpleRequest; import io.grpc.benchmarks.proto.Messages.SimpleResponse; import io.grpc.internal.GrpcUtil; import io.grpc.netty.GrpcSslContexts; import io.grpc.netty.NegotiationType; import io.grpc.netty.NettyChannelBuilder; import io.grpc.okhttp.OkHttpChannelBuilder; import io.grpc.okhttp.internal.Platform; import io.grpc.testing.TestUtils; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.EpollDomainSocketChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.unix.DomainSocketAddress; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import org.HdrHistogram.Histogram; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketAddress; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import javax.net.ssl.SSLSocketFactory; /** * Utility methods to support benchmarking classes. */ public final class Utils { private static final String UNIX_DOMAIN_SOCKET_PREFIX = "unix: // The histogram can record values between 1 microsecond and 1 min. public static final long HISTOGRAM_MAX_VALUE = 60000000L; // Value quantization will be no more than 1%. See the README of HdrHistogram for more details. public static final int HISTOGRAM_PRECISION = 2; public static final int DEFAULT_FLOW_CONTROL_WINDOW = NettyChannelBuilder.DEFAULT_FLOW_CONTROL_WINDOW; private Utils() { } public static boolean parseBoolean(String value) { return value.isEmpty() || Boolean.parseBoolean(value); } /** * Parse a {@link SocketAddress} from the given string. */ public static SocketAddress parseSocketAddress(String value) { if (value.startsWith(UNIX_DOMAIN_SOCKET_PREFIX)) { // Unix Domain Socket address. // Create the underlying file for the Unix Domain Socket. String filePath = value.substring(UNIX_DOMAIN_SOCKET_PREFIX.length()); File file = new File(filePath); if (!file.isAbsolute()) { throw new IllegalArgumentException("File path must be absolute: " + filePath); } try { if (file.createNewFile()) { // If this application created the file, delete it when the application exits. file.deleteOnExit(); } } catch (IOException ex) { throw new RuntimeException(ex); } // Create the SocketAddress referencing the file. return new DomainSocketAddress(file); } else { // Standard TCP/IP address. String[] parts = value.split(":", 2); if (parts.length < 2) { throw new IllegalArgumentException( "Address must be a unix:// path or be in the form host:port. Got: " + value); } String host = parts[0]; int port = Integer.parseInt(parts[1]); return new InetSocketAddress(host, port); } } /** * Create a {@link ManagedChannel} for the given parameters. */ public static ManagedChannel newClientChannel(Transport transport, SocketAddress address, boolean tls, boolean testca, @Nullable String authorityOverride, boolean useDefaultCiphers, int flowControlWindow, boolean directExecutor) throws IOException { if (transport == Transport.OK_HTTP) { InetSocketAddress addr = (InetSocketAddress) address; OkHttpChannelBuilder builder = OkHttpChannelBuilder .forAddress(addr.getHostName(), addr.getPort()); if (directExecutor) { builder.directExecutor(); } builder.negotiationType(tls ? io.grpc.okhttp.NegotiationType.TLS : io.grpc.okhttp.NegotiationType.PLAINTEXT); if (tls) { SSLSocketFactory factory; if (testca) { builder.overrideAuthority( GrpcUtil.authorityFromHostAndPort(authorityOverride, addr.getPort())); try { factory = TestUtils.newSslSocketFactoryForCa( Platform.get().getProvider(), TestUtils.loadCert("ca.pem")); } catch (Exception e) { throw new RuntimeException(e); } } else { factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } builder.sslSocketFactory(factory); } if (authorityOverride != null) { builder.overrideAuthority(authorityOverride); } return builder.build(); } // It's a Netty transport. SslContext sslContext = null; NegotiationType negotiationType = tls ? NegotiationType.TLS : NegotiationType.PLAINTEXT; if (tls && testca) { File cert = TestUtils.loadCert("ca.pem"); SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient().trustManager(cert); if (transport == Transport.NETTY_NIO) { sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder, SslProvider.JDK); } else { // Native transport with OpenSSL sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder, SslProvider.OPENSSL); } if (useDefaultCiphers) { sslContextBuilder.ciphers(null); } sslContext = sslContextBuilder.build(); } final EventLoopGroup group; final Class<? extends io.netty.channel.Channel> channelType; ThreadFactory tf = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("ELG-%d") .build(); switch (transport) { case NETTY_NIO: group = new NioEventLoopGroup(0, tf); channelType = NioSocketChannel.class; break; case NETTY_EPOLL: // These classes only work on Linux. group = new EpollEventLoopGroup(0, tf); channelType = EpollSocketChannel.class; break; case NETTY_UNIX_DOMAIN_SOCKET: // These classes only work on Linux. group = new EpollEventLoopGroup(0, tf); channelType = EpollDomainSocketChannel.class; break; default: // Should never get here. throw new IllegalArgumentException("Unsupported transport: " + transport); } NettyChannelBuilder builder = NettyChannelBuilder .forAddress(address) .eventLoopGroup(group) .channelType(channelType) .negotiationType(negotiationType) .sslContext(sslContext) .flowControlWindow(flowControlWindow); if (authorityOverride != null) { builder.overrideAuthority(authorityOverride); } if (directExecutor) { builder.directExecutor(); } else { // TODO(carl-mastrangelo): This should not be necessary. I don't know where this should be // put. Move it somewhere else, or remove it if no longer necessary. builder.executor(new ForkJoinPool(Runtime.getRuntime().availableProcessors(), new ForkJoinWorkerThreadFactory() { final AtomicInteger num = new AtomicInteger(); @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { ForkJoinWorkerThread thread = defaultForkJoinWorkerThreadFactory.newThread(pool); thread.setDaemon(true); thread.setName("grpc-server-app-" + "-" + num.getAndIncrement()); return thread; } }, UncaughtExceptionHandlers.systemExit(), true /* async */)); } return builder.build(); } /** * Save a {@link Histogram} to a file. */ public static void saveHistogram(Histogram histogram, String filename) throws IOException { File file; PrintStream log = null; try { file = new File(filename); if (file.exists() && !file.delete()) { System.err.println("Failed deleting previous histogram file: " + file.getAbsolutePath()); } log = new PrintStream(new FileOutputStream(file), false); histogram.outputPercentileDistribution(log, 1.0); } finally { if (log != null) { log.close(); } } } /** * Construct a {@link SimpleResponse} for the given request. */ public static SimpleResponse makeResponse(SimpleRequest request) { if (request.getResponseSize() > 0) { if (!Messages.PayloadType.COMPRESSABLE.equals(request.getResponseType())) { throw Status.INTERNAL.augmentDescription("Error creating payload.").asRuntimeException(); } ByteString body = ByteString.copyFrom(new byte[request.getResponseSize()]); Messages.PayloadType type = request.getResponseType(); Payload payload = Payload.newBuilder().setType(type).setBody(body).build(); return SimpleResponse.newBuilder().setPayload(payload).build(); } return SimpleResponse.getDefaultInstance(); } /** * Construct a {@link SimpleRequest} with the specified dimensions. */ public static SimpleRequest makeRequest(Messages.PayloadType payloadType, int reqLength, int respLength) { ByteString body = ByteString.copyFrom(new byte[reqLength]); Payload payload = Payload.newBuilder() .setType(payloadType) .setBody(body) .build(); return SimpleRequest.newBuilder() .setResponseType(payloadType) .setResponseSize(respLength) .setPayload(payload) .build(); } /** * Picks a port that is not used right at this moment. * Warning: Not thread safe. May see "BindException: Address already in use: bind" if using the * returned port to create a new server socket when other threads/processes are concurrently * creating new sockets without a specific port. */ public static int pickUnusedPort() { try { ServerSocket serverSocket = new ServerSocket(0); int port = serverSocket.getLocalPort(); serverSocket.close(); return port; } catch (IOException e) { throw new RuntimeException(e); } } }
package com.gdrivefs.test.cases; import java.io.IOException; import java.security.GeneralSecurityException; import net.fusejna.FuseException; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import com.gdrivefs.test.util.DriveBuilder; public class TruncateTest { @Test public void testTruncateChangesSize() throws IOException, GeneralSecurityException, InterruptedException, UnsatisfiedLinkError, FuseException { DriveBuilder builder = new DriveBuilder(); try { { java.io.File test = builder.cleanMountedDirectory(); java.io.File helloFile = new java.io.File(test, "hello.txt"); FileUtils.write(helloFile, "123456789"); Assert.assertEquals(9, helloFile.length()); } builder.flush(); { com.gdrivefs.simplecache.File test = builder.uncleanDriveDirectory(); com.gdrivefs.simplecache.File helloFile = test.getChildren("hello.txt").get(0); Assert.assertEquals(9, helloFile.getSize()); helloFile.truncate(5); Assert.assertEquals(5, helloFile.getSize()); } builder.flush(); { com.gdrivefs.simplecache.File test = builder.uncleanDriveDirectory(); com.gdrivefs.simplecache.File helloFile = test.getChildren("hello.txt").get(0); Assert.assertEquals(5, helloFile.getSize()); } } finally { builder.close(); } } }
package net.simpvp.Portals; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.UUID; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; public class PortalUtils { /** * For teleporting the given player using a specific portal * @param player player who is trying to teleport * @param portal block to check for portal location at */ @SuppressWarnings("deprecation") public static void teleport(Player player, Location portal) { /* Check if the player is trying to teleport again too fast */ if (Portals.justTeleportedEntities.contains(player.getUniqueId())) { return; } Location location = player.getLocation(); Location destination = SQLite.get_other_portal(portal); /* If this portal is not a Portals portal */ if (destination == null) { Portals.instance.getLogger().info(player.getName() + " destination was null."); return; } /* Stop Yaw and Pitch from changing if portal location is not directly from player */ destination.setYaw(location.getYaw()); destination.setPitch(location.getPitch()); /* Make sure a valid portal is at destination */ if (!PortalCheck.is_valid_portal(destination.getBlock())) { Portals.instance.getLogger().info(player.getName() + " destination portal frame is missing."); return; } Portals.instance.getLogger().info("Teleporting " + player.getName() + " to " + destination.getWorld().getName() + " " + destination.getBlockX() + " " + destination.getBlockY() + " " + destination.getBlockZ()); Location fLoc = new Location(destination.getWorld(), destination.getBlockX(), destination.getBlockY() - 1, destination.getBlockZ()); player.sendBlockChange(fLoc, fLoc.getBlock().getType(), fLoc.getBlock().getData()); fLoc = new Location(destination.getWorld(), destination.getBlockX(), destination.getBlockY(), destination.getBlockZ()); player.sendBlockChange(fLoc, fLoc.getBlock().getType(), fLoc.getBlock().getData()); player.teleport(destination); teleportNearby(portal, destination, player); /* Fix players from being stuck sneaking after a teleport*/ unsneak(player); setTeleported(player); } /** * For teleporting the given player using their current location * @param player player who is trying to teleport */ public static void teleport(Player player) { Location location = player.getLocation(); teleport(player, location); } /** * For limiting portal attempts * Allows two way minecart travel and maybe fixes the instant death bug * @param entity entity to stop from teleporting again too soon */ public static void setTeleported(Entity entity) { final UUID uuid = entity.getUniqueId(); Portals.justTeleportedEntities.add(uuid); Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { Portals.justTeleportedEntities.remove(uuid); } }, 20L); } /** * For stopping a player from being locked sneaking after switching worlds with a Portal * @param player player to unsneak */ public static void unsneak(final Player player) { Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.setSneaking(false); } }, 1L); } /** * Teleports nearby non-player entities through a nearby portal * @param location Location from which someone is being teleported * @param destination Location of the portal to which things are to be teleported * @param player player who used the portal and may have to be teleported again to stop visual bug */ public static void teleportNearby(Location from, final Location destination, Player player) { /* First teleport all entities at the same time as the player * The delay in previous versions seems to cause the duplication bug */ Collection<Entity> nearby = from.getWorld().getNearbyEntities(from, 2, 2, 2); boolean somethingTeleported = false; for (Entity entity : nearby) { if (!TELEPORTABLE_ENTITIES.contains(entity.getType())) continue; entity.teleport(destination); somethingTeleported = true; } /* A bug seems to make all the entities invisible for just the player who used the portal. * Teleporting the player to the original location and then back seems to fix this. */ if (somethingTeleported) { // Only bother reteleporting players if an entity came with them Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.teleport(from); } }, 1L); Portals.instance.getServer().getScheduler().runTaskLater(Portals.instance, new Runnable() { public void run() { player.teleport(destination); } }, 2L); } } private static final HashSet<EntityType> TELEPORTABLE_ENTITIES = new HashSet<EntityType>(Arrays.asList( // EntityType.AREA_EFFECT_CLOUD, // EntityType.ARMOR_STAND, EntityType.ARROW, EntityType.BAT, EntityType.BLAZE, EntityType.BOAT, EntityType.CAT, EntityType.CAVE_SPIDER, EntityType.CHICKEN, EntityType.COW, EntityType.CREEPER, EntityType.DOLPHIN, EntityType.DONKEY, // EntityType.DRAGON_FIREBALL, EntityType.DROPPED_ITEM, EntityType.EGG, EntityType.ELDER_GUARDIAN, // EntityType.ENDER_CRYSTAL, // EntityType.ENDER_DRAGON, EntityType.ENDER_PEARL, // EntityType.ENDER_SIGNAL, EntityType.ENDERMAN, EntityType.ENDERMITE, EntityType.EVOKER, // EntityType.EVOKER_FANGS, EntityType.EXPERIENCE_ORB, // EntityType.FALLING_BLOCK, EntityType.FIREBALL, // EntityType.FIREWORK, // EntityType.FISHING_HOOK, EntityType.FOX, EntityType.GHAST, // EntityType.GIANT, EntityType.GUARDIAN, EntityType.HORSE, EntityType.HUSK, EntityType.ILLUSIONER, EntityType.IRON_GOLEM, // EntityType.ITEM_FRAME, // EntityType.LEASH_HITCH, // EntityType.LIGHTNING, EntityType.LLAMA, // EntityType.LLAMA_SPIT, EntityType.MAGMA_CUBE, EntityType.MINECART, EntityType.MINECART_CHEST, // EntityType.MINECART_COMMAND, EntityType.MINECART_FURNACE, EntityType.MINECART_HOPPER, // EntityType.MINECART_MOB_SPAWNER, EntityType.MINECART_TNT, EntityType.MULE, EntityType.MUSHROOM_COW, EntityType.OCELOT, // EntityType.PAINTING, EntityType.PANDA, EntityType.PARROT, // EntityType.PHANTOM, EntityType.PIG, EntityType.PIG_ZOMBIE, EntityType.PILLAGER, // EntityType.PLAYER, EntityType.POLAR_BEAR, EntityType.PRIMED_TNT, EntityType.PUFFERFISH, EntityType.RABBIT, EntityType.RAVAGER, EntityType.SALMON, EntityType.SHEEP, EntityType.SHULKER, // EntityType.SHULKER_BULLET, EntityType.SILVERFISH, EntityType.SKELETON, EntityType.SKELETON_HORSE, EntityType.SLIME, // EntityType.SMALL_FIREBALL, // EntityType.SNOWBALL, EntityType.SNOWMAN, // EntityType.SPECTRAL_ARROW, EntityType.SPIDER, // EntityType.SPLASH_POTION, EntityType.SQUID, EntityType.STRAY, // EntityType.THROWN_EXP_BOTTLE, EntityType.TRADER_LLAMA, // EntityType.TRIDENT, EntityType.TROPICAL_FISH, EntityType.TURTLE, // EntityType.UNKNOWN, EntityType.VEX, EntityType.VILLAGER, EntityType.VINDICATOR, EntityType.WANDERING_TRADER, EntityType.WITCH, // EntityType.WITHER, EntityType.WITHER_SKELETON, // EntityType.WITHER_SKULL, EntityType.WOLF, EntityType.ZOMBIE, EntityType.ZOMBIE_HORSE, EntityType.ZOMBIE_VILLAGER )); }
package net.tomp2p.dht; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.concurrent.DefaultEventExecutorGroup; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.Random; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.tomp2p.connection.Bindings; import net.tomp2p.connection.ChannelClientConfiguration; import net.tomp2p.connection.ChannelServerConfiguration; import net.tomp2p.connection.PeerException; import net.tomp2p.connection.PeerException.AbortCause; import net.tomp2p.futures.BaseFuture; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.FutureBootstrap; import net.tomp2p.futures.FutureDirect; import net.tomp2p.futures.FutureDone; import net.tomp2p.futures.FuturePeerConnection; import net.tomp2p.futures.FutureResponse; import net.tomp2p.message.Buffer; import net.tomp2p.p2p.AutomaticFuture; import net.tomp2p.p2p.DefaultBroadcastHandler; import net.tomp2p.p2p.Peer; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.p2p.RequestP2PConfiguration; import net.tomp2p.p2p.RoutingConfiguration; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number320; import net.tomp2p.peers.Number480; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerMap; import net.tomp2p.peers.PeerStatistic; import net.tomp2p.rpc.DigestResult; import net.tomp2p.rpc.ObjectDataReply; import net.tomp2p.rpc.RawDataReply; import net.tomp2p.storage.Data; import net.tomp2p.utils.Utils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestDHT { final private static Random rnd = new Random(42L); private static final Logger LOG = LoggerFactory.getLogger(TestDHT.class); @Test public void testPutTwo() throws Exception { PeerDHT master = null; try { PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); final Data data1 = new Data(new byte[1]); data1.ttlSeconds(3); FuturePut futurePut = master.put(Number160.createHash("test")).data(data1).start(); futurePut.awaitUninterruptibly(); Assert.assertEquals(true, futurePut.isSuccess()); FutureGet futureGet = peers[1].get(Number160.createHash("test")).start(); futureGet.awaitUninterruptibly(); Assert.assertEquals(true, futureGet.isSuccess()); // LOG.error("done"); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutVersion() throws Exception { final Random rnd = new Random(42L); PeerDHT master = null; try { PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); final Data data1 = new Data(new byte[1]); data1.ttlSeconds(3); FuturePut futurePut = master.put(Number160.createHash("test")).versionKey(Number160.MAX_VALUE) .data(data1).start(); futurePut.awaitUninterruptibly(); Assert.assertEquals(true, futurePut.isSuccess()); Map<Number640, Data> map = peers[0].storageLayer().get(); Assert.assertEquals(Number160.MAX_VALUE, map.entrySet().iterator().next().getKey().versionKey()); LOG.error("done"); } finally { if (master != null) { master.shutdown().awaitListenersUninterruptibly(); } } } @Test public void testPutPerforomance() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); for (int i = 0; i < 500; i++) { long start = System.currentTimeMillis(); FuturePut fp = peers[444].put(Number160.createHash("1")).data(new Data("test")).start(); fp.awaitUninterruptibly(); fp.futureRequests().awaitUninterruptibly(); for (FutureResponse fr : fp.futureRequests().completed()) { LOG.error(fr + " / " + fr.request()); } long stop = System.currentTimeMillis(); System.err.println("Test " + fp.failedReason() + " / " + (stop - start) + "ms"); Assert.assertEquals(true, fp.isSuccess()); } } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPut() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); FuturePut fp = peers[444].put(peers[30].peerID()) .data(Number160.createHash("test"), new Number160(5), data).requestP2PConfiguration(pc) .routingConfiguration(rc).start(); fp.awaitUninterruptibly(); fp.futureRequests().awaitUninterruptibly(); System.err.println("Test " + fp.failedReason()); Assert.assertEquals(true, fp.isSuccess()); peers[30].peerBean().peerMap(); // search top 3 TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createComparator(peers[30] .peer().peerID())); int i = 0; for (PeerDHT node : peers) { tmp.put(node.peer().peerAddress(), i); i++; } Entry<PeerAddress, Integer> e = tmp.pollFirstEntry(); System.err.println("1 (" + e.getValue() + ")" + e.getKey()); Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress()); testForArray(peers[e.getValue()], peers[30].peerID(), true); e = tmp.pollFirstEntry(); System.err.println("2 (" + e.getValue() + ")" + e.getKey()); testForArray(peers[e.getValue()], peers[30].peerID(), true); e = tmp.pollFirstEntry(); System.err.println("3 " + e.getKey()); testForArray(peers[e.getValue()], peers[30].peerID(), true); e = tmp.pollFirstEntry(); System.err.println("4 " + e.getKey()); testForArray(peers[e.getValue()], peers[30].peerID(), false); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGetAlone() throws Exception { PeerDHT master = null; try { master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start(); FuturePut fdht = master.put(Number160.ONE).data(new Data("hallo")).start(); fdht.awaitUninterruptibly(); fdht.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht.isSuccess()); FutureGet fdht2 = master.get(Number160.ONE).start(); fdht2.awaitUninterruptibly(); System.err.println(fdht2.failedReason()); Assert.assertEquals(true, fdht2.isSuccess()); Data tmp = fdht2.data(); Assert.assertEquals("hallo", tmp.object().toString()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutTimeout() throws Exception { PeerDHT master = null; try { Peer pmaster = new PeerBuilder(new Number160(rnd)).ports(4001).start(); master = new PeerBuilderDHT(pmaster).storage(new StorageMemory(1)).start(); Data data = new Data("hallo"); data.ttlSeconds(1); FuturePut fdht = master.put(Number160.ONE).data(data).start(); fdht.awaitUninterruptibly(); fdht.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht.isSuccess()); Thread.sleep(3000); FutureGet fdht2 = master.get(Number160.ONE).start(); fdht2.awaitUninterruptibly(); System.err.println(fdht2.failedReason()); //we get an empty result, this means it did not fail, just it did not return anything Assert.assertEquals(true, fdht2.isSuccess()); Data tmp = fdht2.data(); Assert.assertNull(tmp); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPut2() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(0, 0, 1); RequestP2PConfiguration pc = new RequestP2PConfiguration(1, 0, 0); FuturePut fdht = peers[444].put(peers[30].peerID()).data(new Number160(5), data) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fdht.awaitUninterruptibly(); fdht.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fdht.isSuccess()); peers[30].peerBean().peerMap(); // search top 3 TreeMap<PeerAddress, Integer> tmp = new TreeMap<PeerAddress, Integer>(PeerMap.createComparator(peers[30] .peerID())); int i = 0; for (PeerDHT node : peers) { tmp.put(node.peerAddress(), i); i++; } Entry<PeerAddress, Integer> e = tmp.pollFirstEntry(); Assert.assertEquals(peers[e.getValue()].peerAddress(), peers[30].peerAddress()); testForArray(peers[e.getValue()], peers[30].peerID(), true); e = tmp.pollFirstEntry(); testForArray(peers[e.getValue()], peers[30].peerID(), false); e = tmp.pollFirstEntry(); testForArray(peers[e.getValue()], peers[30].peerID(), false); e = tmp.pollFirstEntry(); testForArray(peers[e.getValue()], peers[30].peerID(), false); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGet() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); Data data = new Data(new byte[44444]); FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); rc = new RoutingConfiguration(0, 0, 10, 1); pc = new RequestP2PConfiguration(1, 0, 0); FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(1, fget.rawData().size()); Assert.assertEquals(true, fget.isMinReached()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutConvert() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); Data data = new Data(new byte[44444]); Map<Number160, Data> tmp = new HashMap<Number160, Data>(); tmp.put(new Number160(5), data); FuturePut fput = peers[444].put(peers[30].peerID()).dataMapContent(tmp) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); System.err.println(fput.failedReason()); Assert.assertEquals(true, fput.isSuccess()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGet2() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); Data data = new Data(new byte[44444]); FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); rc = new RoutingConfiguration(4, 0, 10, 1); pc = new RequestP2PConfiguration(4, 0, 0); FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(3, fget.rawData().size()); Assert.assertEquals(false, fget.isMinReached()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGet3() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); rc = new RoutingConfiguration(1, 0, 10, 1); pc = new RequestP2PConfiguration(1, 0, 0); for (int i = 0; i < 1000; i++) { FutureGet fget = peers[100 + i].get(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc) .start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(1, fget.rawData().size()); Assert.assertEquals(true, fget.isMinReached()); } } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGetRemove() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); FuturePut fput = peers[444].put(peers[30].peerID()).domainKey(Number160.createHash("test")) .data(new Number160(5), data).routingConfiguration(rc).requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); rc = new RoutingConfiguration(4, 0, 10, 1); pc = new RequestP2PConfiguration(4, 0, 0); FutureRemove frem = peers[222].remove(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start(); frem.awaitUninterruptibly(); Assert.assertEquals(true, frem.isSuccess()); Assert.assertEquals(3, frem.rawKeys().size()); FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start(); fget.awaitUninterruptibly(); Assert.assertEquals(false, fget.isSuccess()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutGetRemove2() throws Exception { PeerDHT master = null; try { // rnd.setSeed(253406013991563L); // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); FuturePut fput = peers[444].put(peers[30].peerID()).data(new Number160(5), data) .domainKey(Number160.createHash("test")).routingConfiguration(rc) .requestP2PConfiguration(pc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); System.err.println("remove"); rc = new RoutingConfiguration(4, 0, 10, 1); pc = new RequestP2PConfiguration(4, 0, 0); FutureRemove frem = peers[222].remove(peers[30].peerID()).returnResults() .domainKey(Number160.createHash("test")).contentKey(new Number160(5)) .routingConfiguration(rc).requestP2PConfiguration(pc).start(); frem.awaitUninterruptibly(); Assert.assertEquals(true, frem.isSuccess()); Assert.assertEquals(3, frem.rawData().size()); System.err.println("get"); rc = new RoutingConfiguration(4, 0, 0, 1); pc = new RequestP2PConfiguration(4, 0, 0); FutureGet fget = peers[555].get(peers[30].peerID()).domainKey(Number160.createHash("test")) .contentKey(new Number160(5)).routingConfiguration(rc).requestP2PConfiguration(pc).start(); fget.awaitUninterruptibly(); Assert.assertEquals(false, fget.isSuccess()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testDirect() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); final AtomicInteger ai = new AtomicInteger(0); for (int i = 0; i < peers.length; i++) { peers[i].peer().objectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { ai.incrementAndGet(); return "ja"; } }); } // do testing FutureSend fdir = peers[400].send(new Number160(rnd)).object("hallo").start(); fdir.awaitUninterruptibly(); System.err.println(fdir.failedReason()); Assert.assertEquals(true, fdir.isSuccess()); Assert.assertEquals(true, ai.get() >= 3 && ai.get() <= 6); System.err.println("called: " + ai.get()); Assert.assertEquals("ja", fdir.object()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testAddListGet() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo1"; Data data1 = new Data(toStore1.getBytes()); Data data2 = new Data(toStore2.getBytes()); FuturePut fput = peers[30].add(nr).data(data1).list(true).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")"); fput = peers[50].add(nr).data(data2).list(true).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")"); FutureGet fget = peers[77].get(nr).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); // majority voting with getDataMap is not possible since we create // random content key on the recipient Assert.assertEquals(2, fget.rawData().values().iterator().next().values().size()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testAddGet() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo2"; Data data1 = new Data(toStore1.getBytes()); Data data2 = new Data(toStore2.getBytes()); FuturePut fput = peers[30].add(nr).data(data1).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")"); fput = peers[50].add(nr).data(data2).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")"); FutureGet fget = peers[77].get(nr).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testDigest() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo2"; String toStore3 = "hallo3"; Data data1 = new Data(toStore1.getBytes()); Data data2 = new Data(toStore2.getBytes()); Data data3 = new Data(toStore3.getBytes()); FuturePut fput = peers[30].add(nr).data(data1).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")"); fput = peers[50].add(nr).data(data2).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")"); fput = peers[51].add(nr).data(data3).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")"); FutureDigest fget = peers[77].digest(nr).all().start(); fget.awaitUninterruptibly(); System.err.println(fget.failedReason()); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(3, fget.digest().keyDigest().size()); Number160 test = new Number160("0x37bb570100c9f5445b534757ebc613a32df3836d"); List<Number160> test2 = new ArrayList<Number160>(); test2.add(test); fget = peers[67].digest(nr).contentKeys(test2).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(1, fget.digest().keyDigest().size()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void removeTestLoop() throws IOException, ClassNotFoundException { for(int i=0;i<100;i++) { System.err.println("removeTestLoop() call nr "+i); removeTest(); } } @Test public void removeTest() throws IOException, ClassNotFoundException { PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); String locationKey = "location"; String contentKey = "content"; String data = "testme"; // data.generateVersionKey(); p2.put(Number160.createHash(locationKey)).data(Number160.createHash(contentKey), new Data(data)) .versionKey(Number160.ONE).start().awaitUninterruptibly(); FutureRemove futureRemove = p1.remove(Number160.createHash(locationKey)).domainKey(Number160.ZERO) .contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start(); futureRemove.awaitUninterruptibly(); FutureDigest futureDigest = p1.digest(Number160.createHash(locationKey)).domainKey(Number160.ZERO) .contentKey(Number160.createHash(contentKey)).versionKey(Number160.ONE).start(); futureDigest.awaitUninterruptibly(); Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testDigest2() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo2"; String toStore3 = "hallo3"; Data data1 = new Data(toStore1.getBytes()); Data data2 = new Data(toStore2.getBytes()); Data data3 = new Data(toStore3.getBytes()); Number160 key1 = new Number160(1); Number160 key2 = new Number160(2); Number160 key3 = new Number160(3); FuturePut fput = peers[30].put(nr).data(key1, data1).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore1 + " (" + fput.isSuccess() + ")"); fput = peers[50].put(nr).data(key2, data2).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore2 + " (" + fput.isSuccess() + ")"); fput = peers[51].put(nr).data(key3, data3).start(); fput.awaitUninterruptibly(); System.out.println("added: " + toStore3 + " (" + fput.isSuccess() + ")"); Number640 from = new Number640(nr, Number160.ZERO, Number160.ZERO, Number160.ZERO); Number640 to = new Number640(nr, Number160.MAX_VALUE, Number160.MAX_VALUE, Number160.MAX_VALUE); FutureDigest fget = peers[77].digest(nr).from(from).to(to).returnNr(1).start(); fget.awaitUninterruptibly(); System.err.println(fget.failedReason()); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(1, fget.digest().keyDigest().size()); Assert.assertEquals(key1, fget.digest().keyDigest().keySet().iterator().next().contentKey()); fget = peers[67].digest(nr).from(from).to(to).returnNr(1).descending().start(); fget.awaitUninterruptibly(); System.err.println(fget.failedReason()); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(1, fget.digest().keyDigest().size()); Assert.assertEquals(key3, fget.digest().keyDigest().keySet().iterator().next().contentKey()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testDigest3() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // initialize test data Number160 lKey = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo2"; String toStore3 = "hallo3"; Data data1 = new Data(toStore1.getBytes()); Data data2 = new Data(toStore2.getBytes()); Data data3 = new Data(toStore3.getBytes()); Number160 ckey = new Number160(rnd); data1.addBasedOn(Number160.ONE); Number160 versionKey1 = new Number160(1, data1.hash()); data2.addBasedOn(versionKey1); Number160 versionKey2 = new Number160(2, data2.hash()); data3.addBasedOn(versionKey2); Number160 versionKey3 = new Number160(3, data3.hash()); // put test data FuturePut fput = peers[30].put(lKey).data(ckey, data1, versionKey1).start(); fput.awaitUninterruptibly(); fput = peers[50].put(lKey).data(ckey, data2, versionKey2).start(); fput.awaitUninterruptibly(); fput = peers[51].put(lKey).data(ckey, data3, versionKey3).start(); fput.awaitUninterruptibly(); // get digest FutureDigest fget = peers[77].digest(lKey).all().start(); fget.awaitUninterruptibly(); DigestResult dr = fget.digest(); NavigableMap<Number640, Collection<Number160>> map = dr.keyDigest(); // verify fetched digest Entry<Number640, Collection<Number160>> e1 = map.pollFirstEntry(); Assert.assertEquals(Number160.ONE, e1.getValue().iterator().next()); Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey1), e1.getKey()); Entry<Number640, Collection<Number160>> e2 = map.pollFirstEntry(); Assert.assertEquals(versionKey1, e2.getValue().iterator().next()); Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey2), e2.getKey()); Entry<Number640, Collection<Number160>> e3 = map.pollFirstEntry(); Assert.assertEquals(versionKey2, e3.getValue().iterator().next()); Assert.assertEquals(new Number640(lKey, Number160.ZERO, ckey, versionKey2), e3.getKey()); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testDigest4() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // initialize test data Number160 lKey = new Number160(rnd); Number160 dKey = new Number160(rnd); Number160 ckey = new Number160(rnd); NavigableMap<Number640, Data> dataMap = new TreeMap<Number640, Data>(); Number160 bKey = Number160.ONE; for (int i = 0; i < 10; i++) { Data data = new Data(UUID.randomUUID()); data.addBasedOn(bKey); Number160 vKey = new Number160(i, data.hash()); dataMap.put(new Number640(lKey, dKey, ckey, vKey), data); bKey = vKey; } // put test data for (Number640 key : dataMap.keySet()) { FuturePut fput = peers[rnd.nextInt(100)].put(lKey).domainKey(dKey) .data(ckey, dataMap.get(key)).versionKey(key.versionKey()).start(); fput.awaitUninterruptibly(); } // get digest FutureDigest fget = peers[rnd.nextInt(100)].digest(lKey) .from(new Number640(lKey, dKey, ckey, Number160.ZERO)) .to(new Number640(lKey, dKey, ckey, Number160.MAX_VALUE)).start(); fget.awaitUninterruptibly(); DigestResult dr = fget.digest(); NavigableMap<Number640, Collection<Number160>> fetchedDataMap = dr.keyDigest(); // verify fetched digest Assert.assertEquals(dataMap.size(), fetchedDataMap.size()); for (Number640 key : dataMap.keySet()) { Assert.assertTrue(fetchedDataMap.containsKey(key)); Assert.assertEquals(dataMap.get(key).basedOnSet().iterator().next(), fetchedDataMap.get(key) .iterator().next()); } } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testData() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing ByteBuf c = Unpooled.buffer(); c.writeInt(77); Buffer b = new Buffer(c); peers[50].peer().rawDataReply(new RawDataReply() { @Override public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) { System.err.println(requestBuffer.buffer().readInt()); ByteBuf c = Unpooled.buffer(); c.writeInt(88); Buffer ret = new Buffer(c); return ret; } }); FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).buffer(b).start(); fd.await(); if (fd.buffer() == null) { System.err.println("damm"); Assert.fail(); } int read = fd.buffer().buffer().readInt(); Assert.assertEquals(88, read); System.err.println("done"); // for(FutureBootstrap fb:tmp) // fb.awaitUninterruptibly(); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testData2() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(200, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing ByteBuf c = Unpooled.buffer(); c.writeInt(77); Buffer b = new Buffer(c); peers[50].peer().rawDataReply(new RawDataReply() { @Override public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) { System.err.println("got it"); return requestBuffer; } }); FutureDirect fd = master.peer().sendDirect(peers[50].peerAddress()).buffer(b).start(); fd.await(); System.err.println("done1"); Assert.assertEquals(true, fd.isSuccess()); Assert.assertNull(fd.buffer()); // int read = fd.getBuffer().readInt(); // Assert.assertEquals(88, read); System.err.println("done2"); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testObjectLoop() throws Exception { for (int i = 0; i < 1000; i++) { System.err.println("nr: " + i); testObject(); } } @Test public void testObject() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); String toStore1 = "hallo1"; String toStore2 = "hallo2"; Data data1 = new Data(toStore1); Data data2 = new Data(toStore2); System.err.println("begin add : "); FuturePut fput = peers[30].add(nr).data(data1).start(); fput.awaitUninterruptibly(); System.err.println("stop added: " + toStore1 + " (" + fput.isSuccess() + ")"); fput = peers[50].add(nr).data(data2).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); System.err.println("added: " + toStore2 + " (" + fput.isSuccess() + ")"); FutureGet fget = peers[77].get(nr).all().start(); fget.awaitUninterruptibly(); fget.futureRequests().awaitUninterruptibly(); if (!fget.isSuccess()) System.err.println(fget.failedReason()); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(2, fget.dataMap().size()); System.err.println("got it"); } finally { if (master != null) { master.shutdown().awaitListenersUninterruptibly(); } } } @Test public void testMaintenanceInit() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRoutingIndirect(peers); // do testing PeerStatistic peerStatatistic = master.peerBean().peerMap() .nextForMaintenance(new ArrayList<PeerAddress>()); Assert.assertNotEquals(master.peerAddress(), peerStatatistic.peerAddress()); Thread.sleep(10000); System.err.println("DONE"); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testAddGetPermits() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(2000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing Number160 nr = new Number160(rnd); List<FuturePut> list = new ArrayList<FuturePut>(); for (int i = 0; i < peers.length; i++) { String toStore1 = "hallo" + i; Data data1 = new Data(toStore1.getBytes()); FuturePut fput = peers[i].add(nr).data(data1).start(); list.add(fput); } for (FuturePut futureDHT : list) { futureDHT.awaitUninterruptibly(); Assert.assertEquals(true, futureDHT.isSuccess()); } System.err.println("DONE"); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testhalt() throws Exception { PeerDHT master1 = null; PeerDHT master2 = null; PeerDHT master3 = null; try { master1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4001).start()).start(); master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start(); master3 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4003).start()).start(); // perfect routing master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null); master1.peerBean().peerMap().peerFound(master3.peerAddress(), null, null); master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null); master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null); master3.peerBean().peerMap().peerFound(master1.peerAddress(), null, null); master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null); Number160 id = master2.peerID(); Data data = new Data(new byte[44444]); RoutingConfiguration rc = new RoutingConfiguration(2, 10, 2); RequestP2PConfiguration pc = new RequestP2PConfiguration(3, 5, 0); FuturePut fput = master1.put(id).data(new Number160(5), data).domainKey(Number160.createHash("test")) .requestP2PConfiguration(pc).routingConfiguration(rc).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); // Collection<Number160> tmp = new ArrayList<Number160>(); // tmp.add(new Number160(5)); Assert.assertEquals(true, fput.isSuccess()); // search top 3 master2.shutdown().await(); FutureGet fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc) .domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); master1.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown")); master3.peerBean().peerMap().peerFailed(master2.peerAddress(), new PeerException(AbortCause.SHUTDOWN, "shutdown")); master2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).p2pId(1).ports(4002).start()).start(); master1.peerBean().peerMap().peerFound(master2.peerAddress(), null, null); master3.peerBean().peerMap().peerFound(master2.peerAddress(), null, null); master2.peerBean().peerMap().peerFound(master1.peerAddress(), null, null); master2.peerBean().peerMap().peerFound(master3.peerAddress(), null, null); System.err.println("no more exceptions here!!"); fget = master1.get(id).routingConfiguration(rc).requestP2PConfiguration(pc) .domainKey(Number160.createHash("test")).contentKey(new Number160(5)).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); } finally { if (master1 != null) { master1.shutdown().await(); } if (master2 != null) { master2.shutdown().await(); } if (master3 != null) { master3.shutdown().await(); } } } @Test public void testObjectSendExample() throws Exception { Peer p1 = null; Peer p2 = null; try { p1 = new PeerBuilder(new Number160(rnd)).ports(4001).start(); p2 = new PeerBuilder(new Number160(rnd)).ports(4002).start(); // attach reply handler p2.objectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { System.out.println("request [" + request + "]"); return "world"; } }); FutureDirect futureData = p1.sendDirect(p2.peerAddress()).object("hello").start(); futureData.awaitUninterruptibly(); System.out.println("reply [" + futureData.object() + "]"); } finally { if (p1 != null) { p1.shutdown().await(); } if (p2 != null) { p2.shutdown().await(); } } } @Test public void testObjectSend() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(500, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); for (int i = 0; i < peers.length; i++) { System.err.println("node " + i); peers[i].peer().objectDataReply(new ObjectDataReply() { @Override public Object reply(PeerAddress sender, Object request) throws Exception { return request; } }); peers[i].peer().rawDataReply(new RawDataReply() { @Override public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean complete) throws Exception { return requestBuffer; } }); } // do testing System.err.println("round start"); Random rnd = new Random(42L); byte[] toStore1 = new byte[10 * 1024]; for (int j = 0; j < 5; j++) { System.err.println("round " + j); for (int i = 0; i < peers.length - 1; i++) { send1(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)], toStore1, 100); send2(peers[rnd.nextInt(peers.length)], peers[rnd.nextInt(peers.length)], Unpooled.wrappedBuffer(toStore1), 100); System.err.println("round1 " + i); } } System.err.println("DONE"); } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testKeys() throws Exception { final Random rnd = new Random(42L); PeerDHT p1 = null; PeerDHT p2 = null; try { Number160 n1 = new Number160(rnd); Data d1 = new Data("hello"); Data d2 = new Data("world!"); // setup (step 1) p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start(); FuturePut fput = p1.add(n1).data(d1).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); // test (step 2) fput = p1.add(n1).data(d2).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); FutureGet fget = p2.get(n1).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(2, fget.dataMap().size()); // test (step 3) FutureRemove frem = p1.remove(n1).contentKey(d2.hash()).start(); frem.awaitUninterruptibly(); Assert.assertEquals(true, frem.isSuccess()); fget = p2.get(n1).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(1, fget.dataMap().size()); // test (step 4) fput = p1.add(n1).data(d2).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); fget = p2.get(n1).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(2, fget.dataMap().size()); // test (remove all) frem = p1.remove(n1).contentKey(d1.hash()).start(); frem.awaitUninterruptibly(); frem = p1.remove(n1).contentKey(d2.hash()).start(); frem.awaitUninterruptibly(); fget = p2.get(n1).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(0, fget.dataMap().size()); } finally { if (p1 != null) { p1.shutdown().await(); } if (p2 != null) { p2.shutdown().await(); } } } @Test public void testKeys2() throws Exception { final Random rnd = new Random(42L); PeerDHT p1 = null; PeerDHT p2 = null; try { Number160 n1 = new Number160(rnd); Number160 n2 = new Number160(rnd); Data d1 = new Data("hello"); Data d2 = new Data("world!"); // setup (step 1) p1 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).start()).start(); FuturePut fput = p1.put(n1).data(d1).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); p2 = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); // test (step 2) fput = p1.put(n2).data(d2).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); FutureGet fget = p2.get(n2).start(); fget.awaitUninterruptibly(); Assert.assertEquals(1, fget.dataMap().size()); // test (step 3) FutureRemove frem = p1.remove(n2).start(); frem.awaitUninterruptibly(); Assert.assertEquals(true, frem.isSuccess()); fget = p2.get(n2).start(); fget.awaitUninterruptibly(); Assert.assertEquals(0, fget.dataMap().size()); // test (step 4) fput = p1.put(n2).data(d2).start(); fput.awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); fget = p2.get(n2).start(); fget.awaitUninterruptibly(); Assert.assertEquals(1, fget.dataMap().size()); } finally { if (p1 != null) { p1.shutdown().await(); } if (p2 != null) { p2.shutdown().await(); } } } @Test public void testPutGetAll() throws Exception { final AtomicBoolean running = new AtomicBoolean(true); PeerDHT master = null; try { // setup final PeerDHT[] peers = UtilsDHT2.createNodes(100, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); final Number160 key = Number160.createHash("test"); final Data data1 = new Data("test1"); data1.ttlSeconds(3); final Data data2 = new Data("test2"); data2.ttlSeconds(3); // add every second a two values Thread t = new Thread(new Runnable() { @Override public void run() { while (running.get()) { peers[10].add(key).data(data1).start().awaitUninterruptibly(); peers[10].add(key).data(data2).start().awaitUninterruptibly(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); t.start(); // wait until the first data is stored. Thread.sleep(1000); for (int i = 0; i < 30; i++) { FutureGet fget = peers[20 + i].get(key).all().start(); fget.awaitUninterruptibly(); Assert.assertEquals(2, fget.dataMap().size()); Thread.sleep(1000); } } finally { running.set(false); if (master != null) { master.shutdown().await(); } } } /** * This will probably fail on your machine since you have to have eth0 * configured. This testcase is suited for running on the tomp2p.net server * * @throws Exception */ @Test public void testBindings() throws Exception { final Random rnd = new Random(42L); Peer p1 = null; Peer p2 = null; try { // setup (step 1) Bindings b = new Bindings().addInterface("lo"); p1 = new PeerBuilder(new Number160(rnd)).ports(4001).bindings(b).start(); p2 = new PeerBuilder(new Number160(rnd)).ports(4002).bindings(b).start(); FutureBootstrap fb = p2.bootstrap().peerAddress(p1.peerAddress()).start(); fb.awaitUninterruptibly(); Assert.assertEquals(true, fb.isSuccess()); } finally { if (p1 != null) { p1.shutdown().await(); } if (p2 != null) { p2.shutdown().await(); } } } @Test public void testBroadcast() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(1000, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing master.peer().broadcast(Number160.createHash("blub")).udp(false).start(); DefaultBroadcastHandler d = (DefaultBroadcastHandler) master.peer().broadcastRPC().broadcastHandler(); int counter = 0; while (d.getBroadcastCounter() < 900) { Thread.sleep(200); counter++; if (counter > 100) { System.err.println("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter()); Assert.fail("did not broadcast to 1000 peers, but to " + d.getBroadcastCounter()); } } System.err.println("DONE"); } finally { if (master != null) { master.shutdown().await(); } } } // TODO: make this work @Test public void testTooManyOpenFilesInSystem() throws Exception { Peer master = null; Peer slave = null; try { // since we have two peers, we need to reduce the connections -> we // will have 300 * 2 (peer connection) // plus 100 * 2 * 2. The last multiplication is due to discover, // where the recipient creates a connection // with its own limit. Since the limit is 1024 and we stop at 1000 // only for the connection, we may run into // too many open files PeerBuilder masterMaker = new PeerBuilder(new Number160(rnd)).ports(4001); master = masterMaker.enableMaintenance(false).start(); PeerBuilder slaveMaker = new PeerBuilder(new Number160(rnd)).ports(4002); slave = slaveMaker.enableMaintenance(false).start(); System.err.println("peers up and running"); slave.rawDataReply(new RawDataReply() { @Override public Buffer reply(PeerAddress sender, Buffer requestBuffer, boolean last) throws Exception { final byte[] b1 = new byte[10000]; int i = requestBuffer.buffer().getInt(0); ByteBuf buf = Unpooled.wrappedBuffer(b1); buf.setInt(0, i); return new Buffer(buf); } }); List<BaseFuture> list1 = new ArrayList<BaseFuture>(); List<BaseFuture> list2 = new ArrayList<BaseFuture>(); List<FuturePeerConnection> list3 = new ArrayList<FuturePeerConnection>(); for (int i = 0; i < 125; i++) { final byte[] b = new byte[10000]; FuturePeerConnection pc = master.createPeerConnection(slave.peerAddress()); list1.add(master.sendDirect(pc).buffer(new Buffer(Unpooled.wrappedBuffer(b))).start()); list3.add(pc); // pc.close(); } for (int i = 0; i < 20000; i++) { list2.add(master.discover().peerAddress(slave.peerAddress()).start()); final byte[] b = new byte[10000]; byte[] me = Utils.intToByteArray(i); System.arraycopy(me, 0, b, 0, 4); list2.add(master.sendDirect(slave.peerAddress()).buffer(new Buffer(Unpooled.wrappedBuffer(b))) .start()); } for (BaseFuture bf : list1) { bf.awaitListenersUninterruptibly(); if (bf.isFailed()) { System.err.println("WTF " + bf.failedReason()); } else { System.err.print(","); } Assert.assertEquals(true, bf.isSuccess()); } for (FuturePeerConnection pc : list3) { pc.close().awaitListenersUninterruptibly(); } for (BaseFuture bf : list2) { bf.awaitListenersUninterruptibly(); if (bf.isFailed()) { System.err.println("WTF " + bf.failedReason()); } else { System.err.print("."); } Assert.assertEquals(true, bf.isSuccess()); } System.err.println("done!!"); } catch (Exception e) { e.printStackTrace(); } finally { System.err.println("done!1!"); if (master != null) { master.shutdown().await(); } if (slave != null) { slave.shutdown().await(); } } } @Test public void testThreads() throws Exception { PeerDHT master = null; PeerDHT slave = null; try { DefaultEventExecutorGroup eventExecutorGroup = new DefaultEventExecutorGroup(250); ChannelClientConfiguration ccc1 = PeerBuilder.createDefaultChannelClientConfiguration(); ccc1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup)); ChannelServerConfiguration ccs1 = PeerBuilder.createDefaultChannelServerConfiguration(); ccs1.pipelineFilter(new PeerBuilder.EventExecutorGroupFilter(eventExecutorGroup)); master = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4001).channelClientConfiguration(ccc1) .channelServerConfiguration(ccs1).start()).start(); slave = new PeerBuilderDHT(new PeerBuilder(new Number160(rnd)).ports(4002).channelClientConfiguration(ccc1) .channelServerConfiguration(ccs1).start()).start(); master.peer().bootstrap().peerAddress(slave.peerAddress()).start().awaitUninterruptibly(); slave.peer().bootstrap().peerAddress(master.peerAddress()).start().awaitUninterruptibly(); System.err.println("peers up and running"); final int count = 100; final CountDownLatch latch = new CountDownLatch(count); final AtomicBoolean correct = new AtomicBoolean(true); for (int i = 0; i < count; i++) { FuturePut futurePut = master.put(Number160.ONE).data(new Data("test")).start(); futurePut.addListener(new BaseFutureAdapter<FuturePut>() { @Override public void operationComplete(FuturePut future) throws Exception { Thread.sleep(1000); latch.countDown(); System.err.println("block in "+Thread.currentThread().getName()); if(!Thread.currentThread().getName().contains("EventExecutorGroup")) { correct.set(false); } } }); } latch.await(10, TimeUnit.SECONDS); Assert.assertTrue(correct.get()); } finally { System.err.println("done!1!"); if (master != null) { master.shutdown().await(); } if (slave != null) { slave.shutdown().await(); } } } @Test public void removeFromToTest3() throws IOException, ClassNotFoundException { PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); String data = "test"; p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly(); FutureRemove futureRemove = p1.remove(lKey).domainKey(dKey).contentKey(cKey).start(); futureRemove.awaitUninterruptibly(); // check with a normal digest FutureDigest futureDigest = p1.digest(lKey).contentKey(cKey).domainKey(dKey).start(); futureDigest.awaitUninterruptibly(); Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty()); // check with a from/to digest futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start(); futureDigest.awaitUninterruptibly(); Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void removeFromToTest4() throws IOException, ClassNotFoundException { PeerDHT p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).start()).start(); PeerDHT p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()) .start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); String data = "test"; p2.put(lKey).data(cKey, new Data(data)).domainKey(dKey).start().awaitUninterruptibly(); FutureRemove futureRemove = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start(); futureRemove.awaitUninterruptibly(); FutureDigest futureDigest = p1.digest(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO)) .to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start(); futureDigest.awaitUninterruptibly(); // should be empty Assert.assertTrue(futureDigest.digest().keyDigest().isEmpty()); p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } @Test public void testShutdown() throws Exception { PeerDHT master = null; try { // setup Random rnd = new Random(); final int nrPeers = 10; final int port = 4001; // Peer[] peers = Utils2.createNodes(nrPeers, rnd, port); // Peer[] peers = // createAndAttachNodesWithReplicationShortId(nrPeers, port); // Peer[] peers = createNodes(nrPeers, rnd, port, null, true); PeerDHT[] peers = createNodesWithShortId(nrPeers, rnd, port, null); master = peers[0]; UtilsDHT2.perfectRouting(peers); // do testing final int peerTest = 3; peers[peerTest].put(Number160.createHash(1000)).data(new Data("Test")).start().awaitUninterruptibly(); for (int i = 0; i < nrPeers; i++) { for (Data d : peers[i].storageLayer().get().values()) System.out.println("peer[" + i + "]: " + d.object().toString() + " "); } FutureDone<Void> futureShutdown = peers[peerTest].peer().announceShutdown().start(); futureShutdown.awaitUninterruptibly(); // we need to wait a bit, since the quit RPC is a fire and forget // and we return immediately Thread.sleep(2000); peers[peerTest].shutdown().awaitUninterruptibly(); System.out.println("peer " + peerTest + " is shutdown"); for (int i = 0; i < nrPeers; i++) { for (Data d : peers[i].storageLayer().get().values()) System.out.println("peer[" + i + "]: " + d.object().toString() + " "); } } finally { if (master != null) { master.shutdown().await(); } } } @Test public void testPutPreparePutConfirmGet() throws Exception { PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // put data with a prepare flag Data data = new Data("test").prepareFlag(); Number160 locationKey = Number160.createHash("location"); Number160 domainKey = Number160.createHash("domain"); Number160 contentKey = Number160.createHash("content"); Number160 versionKey = Number160.createHash("version"); FuturePut fput = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, data) .domainKey(domainKey).versionKey(versionKey).start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); // get shouldn't see provisional put FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).versionKey(versionKey).start(); fget.awaitUninterruptibly(); Assert.assertEquals(false, fget.isSuccess()); // confirm prepared put Data tmp = new Data(); FuturePut fputConfirm = peers[rnd.nextInt(10)].put(locationKey).data(contentKey, tmp) .domainKey(domainKey).versionKey(versionKey).putConfirm().start(); fputConfirm.awaitUninterruptibly(); fputConfirm.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fputConfirm.isSuccess()); // get should see confirmed put fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey).contentKey(contentKey) .versionKey(versionKey).start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); Assert.assertEquals(data.object(), fget.data().object()); } finally { if (master != null) { master.shutdown().await(); } } } /** * .../2b../4b-5b../7b.................................. * ..................................................... * 0-1-2a-3-4a-5a-6-7a.................................. * * result should be 2b, 5b, 7a, 7b */ @Test public void testGetLatestVersion1() throws Exception { // create test data NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>(); String content0 = generateRandomString(); Number160 vKey0 = generateVersionKey(0, content0); Data data0 = new Data(content0); sortedMap.put(vKey0, data0); String content1 = generateRandomString(); Number160 vKey1 = generateVersionKey(1, content1); Data data1 = new Data(content1); data1.addBasedOn(vKey0); sortedMap.put(vKey1, data1); String content2a = generateRandomString(); Number160 vKey2a = generateVersionKey(2, content2a); Data data2a = new Data(content2a); data2a.addBasedOn(vKey1); sortedMap.put(vKey2a, data2a); String content2b = generateRandomString(); Number160 vKey2b = generateVersionKey(2, content2b); Data data2b = new Data(content2b); data2b.addBasedOn(vKey1); sortedMap.put(vKey2b, data2b); String content3 = generateRandomString(); Number160 vKey3 = generateVersionKey(3, content3); Data data3 = new Data(content3); data3.addBasedOn(vKey2a); sortedMap.put(vKey3, data3); String content4a = generateRandomString(); Number160 vKey4a = generateVersionKey(4, content4a); Data data4a = new Data(content4a); data4a.addBasedOn(vKey3); sortedMap.put(vKey4a, data4a); String content4b = generateRandomString(); Number160 vKey4b = generateVersionKey(4, content4b); Data data4b = new Data(content4b); data4b.addBasedOn(vKey3); sortedMap.put(vKey4b, data4b); String content5a = generateRandomString(); Number160 vKey5a = generateVersionKey(5, content5a); Data data5a = new Data(content5a); data5a.addBasedOn(vKey4a); sortedMap.put(vKey5a, data5a); String content5b = generateRandomString(); Number160 vKey5b = generateVersionKey(5, content5b); Data data5b = new Data(content5b); data5b.addBasedOn(vKey4b); sortedMap.put(vKey5b, data5b); String content6 = generateRandomString(); Number160 vKey6 = generateVersionKey(6, content6); Data data6 = new Data(content6); data6.addBasedOn(vKey5a); sortedMap.put(vKey6, data6); String content7a = generateRandomString(); Number160 vKey7a = generateVersionKey(7, content7a); Data data7a = new Data(content7a); data7a.addBasedOn(vKey6); sortedMap.put(vKey7a, data7a); String content7b = generateRandomString(); Number160 vKey7b = generateVersionKey(7, content7b); Data data7b = new Data(content7b); data7b.addBasedOn(vKey6); sortedMap.put(vKey7b, data7b); PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // put test data Number160 locationKey = Number160.createHash("location"); Number160 domainKey = Number160.createHash("domain"); Number160 contentKey = Number160.createHash("content"); for (Number160 vKey : sortedMap.keySet()) { FuturePut fput = peers[rnd.nextInt(10)].put(locationKey) .data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey) .start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); } // get latest versions FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); // check result Map<Number640, Data> dataMap = fget.dataMap(); Assert.assertEquals(4, dataMap.size()); Number480 key480 = new Number480(locationKey, domainKey, contentKey); Number640 key2b = new Number640(key480, vKey2b); Assert.assertTrue(dataMap.containsKey(key2b)); Assert.assertEquals(data2b.object(), dataMap.get(key2b).object()); Number640 key5b = new Number640(key480, vKey5b); Assert.assertTrue(dataMap.containsKey(key5b)); Assert.assertEquals(data5b.object(), dataMap.get(key5b).object()); Number640 key7a = new Number640(key480, vKey7a); Assert.assertTrue(dataMap.containsKey(key7a)); Assert.assertEquals(data7a.object(), dataMap.get(key7a).object()); Number640 key7b = new Number640(key480, vKey7b); Assert.assertTrue(dataMap.containsKey(key7b)); Assert.assertEquals(data7b.object(), dataMap.get(key7b).object()); // get latest versions with digest FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().withDigest().start(); fgetWithDigest.awaitUninterruptibly(); Assert.assertTrue(fgetWithDigest.isSuccess()); // check digest result DigestResult digestResult = fgetWithDigest.digest(); Assert.assertEquals(12, digestResult.keyDigest().size()); for (Number160 vKey : sortedMap.keySet()) { Number640 key = new Number640(locationKey, domainKey, contentKey, vKey); Assert.assertTrue(digestResult.keyDigest().containsKey(key)); Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest() .get(key).size()); for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) { Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey)); } } } finally { if (master != null) { master.shutdown().await(); } } } /** * .........../5c....................................... * ..................................................... * .../2b../4b-5b./6b................................... * ..................................................... * 0-1-2a-3-4a-5a.-6a-7................................. * * result should be 2b, 5b, 5c, 6b, 7 */ @Test public void testGetLatestVersion2() throws Exception { NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>(); String content0 = generateRandomString(); Number160 vKey0; vKey0 = generateVersionKey(0, content0); Data data0 = new Data(content0); sortedMap.put(vKey0, data0); String content1 = generateRandomString(); Number160 vKey1 = generateVersionKey(1, content1); Data data1 = new Data(content1); data1.addBasedOn(vKey0); sortedMap.put(vKey1, data1); String content2a = generateRandomString(); Number160 vKey2a = generateVersionKey(2, content2a); Data data2a = new Data(content2a); data2a.addBasedOn(vKey1); sortedMap.put(vKey2a, data2a); String content2b = generateRandomString(); Number160 vKey2b = generateVersionKey(2, content2b); Data data2b = new Data(content2b); data2b.addBasedOn(vKey1); sortedMap.put(vKey2b, data2b); String content3 = generateRandomString(); Number160 vKey3 = generateVersionKey(3, content3); Data data3 = new Data(content3); data3.addBasedOn(vKey2a); sortedMap.put(vKey3, data3); String content4a = generateRandomString(); Number160 vKey4a = generateVersionKey(4, content4a); Data data4a = new Data(content4a); data4a.addBasedOn(vKey3); sortedMap.put(vKey4a, data4a); String content4b = generateRandomString(); Number160 vKey4b = generateVersionKey(4, content4b); Data data4b = new Data(content4b); data4b.addBasedOn(vKey3); sortedMap.put(vKey4b, data4b); String content5a = generateRandomString(); Number160 vKey5a = generateVersionKey(5, content5a); Data data5a = new Data(content5a); data5a.addBasedOn(vKey4a); sortedMap.put(vKey5a, data5a); String content5b = generateRandomString(); Number160 vKey5b = generateVersionKey(5, content5b); Data data5b = new Data(content5b); data5b.addBasedOn(vKey4b); sortedMap.put(vKey5b, data5b); String content5c = generateRandomString(); Number160 vKey5c = generateVersionKey(5, content5c); Data data5c = new Data(content5c); data5c.addBasedOn(vKey4b); sortedMap.put(vKey5c, data5c); String content6a = generateRandomString(); Number160 vKey6a = generateVersionKey(6, content6a); Data data6a = new Data(content6a); data6a.addBasedOn(vKey5a); sortedMap.put(vKey6a, data6a); String content6b = generateRandomString(); Number160 vKey6b = generateVersionKey(6, content6b); Data data6b = new Data(content6b); data6b.addBasedOn(vKey5a); sortedMap.put(vKey6b, data6b); String content7 = generateRandomString(); Number160 vKey7 = generateVersionKey(7, content7); Data data7 = new Data(content7); data7.addBasedOn(vKey6a); sortedMap.put(vKey7, data7); PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // put test data Number160 locationKey = Number160.createHash("location"); Number160 domainKey = Number160.createHash("domain"); Number160 contentKey = Number160.createHash("content"); for (Number160 vKey : sortedMap.keySet()) { FuturePut fput = peers[rnd.nextInt(10)].put(locationKey) .data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey) .start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); } // get latest versions FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); // check result Map<Number640, Data> dataMap = fget.dataMap(); Assert.assertEquals(5, dataMap.size()); Number480 key480 = new Number480(locationKey, domainKey, contentKey); Number640 key2b = new Number640(key480, vKey2b); Assert.assertTrue(dataMap.containsKey(key2b)); Assert.assertEquals(data2b.object(), dataMap.get(key2b).object()); Number640 key5b = new Number640(key480, vKey5b); Assert.assertTrue(dataMap.containsKey(key5b)); Assert.assertEquals(data5b.object(), dataMap.get(key5b).object()); Number640 key5c = new Number640(key480, vKey5c); Assert.assertTrue(dataMap.containsKey(key5c)); Assert.assertEquals(data5c.object(), dataMap.get(key5c).object()); Number640 key6b = new Number640(key480, vKey6b); Assert.assertTrue(dataMap.containsKey(key6b)); Assert.assertEquals(data6b.object(), dataMap.get(key6b).object()); Number640 key7 = new Number640(key480, vKey7); Assert.assertTrue(dataMap.containsKey(key7)); Assert.assertEquals(data7.object(), dataMap.get(key7).object()); // get latest versions with digest FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().withDigest().start(); fgetWithDigest.awaitUninterruptibly(); Assert.assertTrue(fgetWithDigest.isSuccess()); // check digest result DigestResult digestResult = fgetWithDigest.digest(); Assert.assertEquals(13, digestResult.keyDigest().size()); for (Number160 vKey : sortedMap.keySet()) { Number640 key = new Number640(locationKey, domainKey, contentKey, vKey); Assert.assertTrue(digestResult.keyDigest().containsKey(key)); Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest() .get(key).size()); for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) { Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey)); } } } finally { if (master != null) { master.shutdown().await(); } } } /** * 0-1-2 * * result should return version 2 */ @Test public void testGetLatestVersion3() throws Exception { NavigableMap<Number160, Data> sortedMap = new TreeMap<Number160, Data>(); String content0 = generateRandomString(); Number160 vKey0; vKey0 = generateVersionKey(0, content0); Data data0 = new Data(content0); sortedMap.put(vKey0, data0); String content1 = generateRandomString(); Number160 vKey1 = generateVersionKey(1, content1); Data data1 = new Data(content1); data1.addBasedOn(vKey0); sortedMap.put(vKey1, data1); String content2 = generateRandomString(); Number160 vKey2 = generateVersionKey(2, content2); Data data2 = new Data(content2); data2.addBasedOn(vKey1); sortedMap.put(vKey2, data2); PeerDHT master = null; try { // setup PeerDHT[] peers = UtilsDHT2.createNodes(10, rnd, 4001); master = peers[0]; UtilsDHT2.perfectRouting(peers); // put test data Number160 locationKey = Number160.createHash("location"); Number160 domainKey = Number160.createHash("domain"); Number160 contentKey = Number160.createHash("content"); for (Number160 vKey : sortedMap.keySet()) { FuturePut fput = peers[rnd.nextInt(10)].put(locationKey) .data(contentKey, sortedMap.get(vKey)).domainKey(domainKey).versionKey(vKey) .start(); fput.awaitUninterruptibly(); fput.futureRequests().awaitUninterruptibly(); Assert.assertEquals(true, fput.isSuccess()); } // get latest versions FutureGet fget = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().start(); fget.awaitUninterruptibly(); Assert.assertEquals(true, fget.isSuccess()); // check result Map<Number640, Data> dataMap = fget.dataMap(); Assert.assertEquals(1, dataMap.size()); Number480 key480 = new Number480(locationKey, domainKey, contentKey); Number640 key2 = new Number640(key480, vKey2); Assert.assertTrue(dataMap.containsKey(key2)); Assert.assertEquals(data2.object(), dataMap.get(key2).object()); // get latest versions with digest FutureGet fgetWithDigest = peers[rnd.nextInt(10)].get(locationKey).domainKey(domainKey) .contentKey(contentKey).getLatest().withDigest().start(); fgetWithDigest.awaitUninterruptibly(); Assert.assertTrue(fgetWithDigest.isSuccess()); // check digest result DigestResult digestResult = fgetWithDigest.digest(); Assert.assertEquals(3, digestResult.keyDigest().size()); for (Number160 vKey : sortedMap.keySet()) { Number640 key = new Number640(locationKey, domainKey, contentKey, vKey); Assert.assertTrue(digestResult.keyDigest().containsKey(key)); Assert.assertEquals(sortedMap.get(vKey).basedOnSet().size(), digestResult.keyDigest() .get(key).size()); for (Number160 bKey : sortedMap.get(vKey).basedOnSet()) { Assert.assertTrue(digestResult.keyDigest().get(key).contains(bKey)); } } } finally { if (master != null) { master.shutdown().await(); } } } private static String generateRandomString() { return UUID.randomUUID().toString(); } private static Number160 generateVersionKey(long basedOnCounter, Serializable object) throws IOException { // get a MD5 hash of the object itself byte[] hash = generateMD5Hash(serializeObject(object)); return new Number160(basedOnCounter, new Number160(Arrays.copyOf(hash, Number160.BYTE_ARRAY_SIZE))); } private static byte[] generateMD5Hash(byte[] data) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } md.reset(); md.update(data, 0, data.length); return md.digest(); } private static byte[] serializeObject(Serializable object) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; byte[] result = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(object); result = baos.toByteArray(); } catch (IOException e) { throw e; } finally { try { if (oos != null) oos.close(); if (baos != null) baos.close(); } catch (IOException e) { throw e; } } return result; } public static PeerDHT[] createNodesWithShortId(int nrOfPeers, Random rnd, int port, AutomaticFuture automaticFuture) throws Exception { if (nrOfPeers < 1) { throw new IllegalArgumentException("Cannot create less than 1 peer"); } final Peer master; PeerDHT[] peers = new PeerDHT[nrOfPeers]; if (automaticFuture != null) { master = new PeerBuilder(new Number160(1111)) .ports(port).start().addAutomaticFuture(automaticFuture); peers[0] = new PeerBuilderDHT(master).start(); } else { master = new PeerBuilder(new Number160(1111)).ports(port) .start(); peers[0] = new PeerBuilderDHT(master).start(); } for (int i = 1; i < nrOfPeers; i++) { if (automaticFuture != null) { Peer peer = new PeerBuilder(new Number160(i)) .masterPeer(master).start().addAutomaticFuture(automaticFuture); peers[i] = new PeerBuilderDHT(peer).start(); } else { Peer peer = new PeerBuilder(new Number160(i)) .masterPeer(master).start(); peers[i] = new PeerBuilderDHT(peer).start(); } } System.err.println("peers created."); return peers; } private void send2(final PeerDHT p1, final PeerDHT p2, final ByteBuf toStore1, final int count) throws IOException { if (count == 0) { return; } Buffer b = new Buffer(toStore1); FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).buffer(b).start(); fd.addListener(new BaseFutureAdapter<FutureDirect>() { @Override public void operationComplete(FutureDirect future) throws Exception { if (future.isFailed()) { // System.err.println(future.getFailedReason()); send2(p1, p2, toStore1, count - 1); } } }); } private void send1(final PeerDHT p1, final PeerDHT p2, final byte[] toStore1, final int count) throws IOException { if (count == 0) { return; } FutureDirect fd = p1.peer().sendDirect(p2.peerAddress()).object(toStore1).start(); fd.addListener(new BaseFutureAdapter<FutureDirect>() { @Override public void operationComplete(FutureDirect future) throws Exception { if (future.isFailed()) { //System.err.println(future.getFailedReason()); send1(p1, p2, toStore1, count - 1); } } }); } private void testForArray(PeerDHT peer, Number160 locationKey, boolean find) { Collection<Number160> tmp = new ArrayList<Number160>(); tmp.add(new Number160(5)); Number640 min = new Number640(locationKey, Number160.createHash("test"), Number160.ZERO, Number160.ZERO); Number640 max = new Number640(locationKey, Number160.createHash("test"), Number160.MAX_VALUE, Number160.MAX_VALUE); Map<Number640, Data> test = peer.storageLayer().get(min, max, -1, true); if (find) { Assert.assertEquals(1, test.size()); Assert.assertEquals( 44444, test.get( new Number640(new Number320(locationKey, Number160.createHash("test")), new Number160(5), Number160.ZERO)).length()); } else Assert.assertEquals(0, test.size()); } }
package solver.constraints.nary; import choco.kernel.ESat; import choco.kernel.common.util.tools.ArrayUtils; import gnu.trove.list.array.TIntArrayList; import solver.Solver; import solver.constraints.IntConstraint; import solver.constraints.propagators.nary.alldifferent.PropAllDiffBC; import solver.constraints.propagators.nary.nValue.PropAtLeastNValues_AC; import solver.constraints.propagators.nary.nValue.PropAtMostNValues_BC; import solver.constraints.propagators.nary.nValue.PropAtMostNValues_Greedy; import solver.constraints.propagators.nary.nValue.PropNValues_Light; import solver.variables.IntVar; import solver.variables.Variable; import java.util.BitSet; /** * NValues constraint * The number of distinct values in the set of variables and within a set of given values is equal to nValues * * @author Jean-Guillaume Fages */ public class NValues extends IntConstraint<IntVar> { /** * NValues constraint * The number of distinct values in vars is exactly nValues * private because the case were all values are not restricted is not tested (i.e. unsafe) * @param vars * @param nValues * @param concernedValues * @param solver */ private NValues(IntVar[] vars, IntVar nValues, TIntArrayList concernedValues, Solver solver) { super(ArrayUtils.append(vars, new IntVar[]{nValues}), solver); addPropagators(new PropNValues_Light(vars, concernedValues, nValues, this, solver)); } /** * NValues constraint * The number of distinct values in vars is exactly nValues * * @param vars * @param nValues * @param solver */ public NValues(IntVar[] vars, IntVar nValues, Solver solver) { this(vars, nValues, getDomainUnion(vars), solver); addPropagators(new PropAtMostNValues_BC(vars, nValues, this, solver)); addPropagators(new PropAtMostNValues_Greedy(vars, nValues, this, solver)); addPropagators(new PropAtLeastNValues_AC(vars, nValues, this, solver)); } private static TIntArrayList getDomainUnion(IntVar[] vars) { TIntArrayList values = new TIntArrayList(); for(IntVar v:vars){ int ub = v.getUB(); for(int i=v.getLB();i<=ub;i=v.nextValue(i)){ if(!values.contains(i)){ values.add(i); } } } return values; } /** * Checks if the constraint is satisfied when all variables are instantiated. * * @param tuple an complete instantiation * @return true iff a solution */ @Override public ESat isSatisfied(int[] tuple) { BitSet values = new BitSet(tuple.length-1); for (int i = 0; i < tuple.length-1; i++) { values.set(tuple[i]); } if(values.cardinality()<=tuple[tuple.length-1]){ return ESat.TRUE; } return ESat.FALSE; } public String toString() { StringBuilder sb = new StringBuilder(32); sb.append("NValue({"); for (int i = 0; i < vars.length-1; i++) { if (i > 0) sb.append(", "); Variable var = vars[i]; sb.append(var); } sb.append(" = "+vars[vars.length-1]); sb.append("})"); return sb.toString(); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ import edu.wpi.first.wpilibj.CounterBase; import edu.wpi.first.wpilibj.DigitalOutput; import hardware.AbsoluteAnalogEncoder; import hardware.SabertoothSpeedController; import hardware.SwervePod; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotSwerve extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ // Temporary solution for defining hardware, used for testing // Joystick _joystick; Encoder _encoder1; AbsoluteAnalogEncoder _digipot1; Encoder _encoder2; AbsoluteAnalogEncoder _digipot2; Encoder _encoder3; AbsoluteAnalogEncoder _digipot3; Encoder _encoder4; AbsoluteAnalogEncoder _digipot4; Talon _turningMotor1; SabertoothSpeedController _driveMotor1; Talon _turningMotor2; SabertoothSpeedController _driveMotor2; Talon _turningMotor3; SabertoothSpeedController _driveMotor3; Talon _turningMotor4; SabertoothSpeedController _driveMotor4; SwervePod _pod1; SwervePod _pod2; SwervePod _pod3; SwervePod _pod4; // Used for triggering oscilloscope reading for step response graphs // DigitalOutput _scopeTrigger = new DigitalOutput(14); public void robotInit() { System.out.println("Initializing robot..."); if (!SabertoothSpeedController.isSerialPortInitialized()) SabertoothSpeedController.initializeSerialPort(9600); _joystick = new Joystick(1); // TODO: Handle hardware differently // _encoder1 = new Encoder(1, 2, false, CounterBase.EncodingType.k1X); _digipot1 = new AbsoluteAnalogEncoder(2, 0.204, 4.96, 0.0); _encoder2 = new Encoder(3, 4, false, CounterBase.EncodingType.k1X); _digipot2 = new AbsoluteAnalogEncoder(1, 0.204, 4.96, 0.0); _encoder3 = new Encoder(5, 6, false, CounterBase.EncodingType.k1X); _digipot3 = new AbsoluteAnalogEncoder(3, 0.204, 4.96, 333); _encoder4 = new Encoder(7, 8, false, CounterBase.EncodingType.k1X); _digipot4 = new AbsoluteAnalogEncoder(4, 0.204, 4.96, 20); _turningMotor1 = new Talon(1); _driveMotor1 = new SabertoothSpeedController(SabertoothSpeedController.SabertoothAddress.SABERTOOTH_TWO, SabertoothSpeedController.SabertoothMotor.SABERTOOTH_MOTOR_ONE); _turningMotor2 = new Talon(2); _driveMotor2 = new SabertoothSpeedController(SabertoothSpeedController.SabertoothAddress.SABERTOOTH_TWO, SabertoothSpeedController.SabertoothMotor.SABERTOOTH_MOTOR_TWO); _turningMotor3 = new Talon(3); _driveMotor3 = new SabertoothSpeedController(SabertoothSpeedController.SabertoothAddress.SABERTOOTH_ONE, SabertoothSpeedController.SabertoothMotor.SABERTOOTH_MOTOR_ONE); _turningMotor4 = new Talon(4); _driveMotor4 = new SabertoothSpeedController(SabertoothSpeedController.SabertoothAddress.SABERTOOTH_ONE, SabertoothSpeedController.SabertoothMotor.SABERTOOTH_MOTOR_TWO); _pod1 = new SwervePod(_turningMotor1, _driveMotor1, _encoder1, _digipot1); _pod2 = new SwervePod(_turningMotor2, _driveMotor2, _encoder2, _digipot2); _pod3 = new SwervePod(_turningMotor3, _driveMotor3, _encoder3, _digipot3); _pod4 = new SwervePod(_turningMotor4, _driveMotor4, _encoder4, _digipot4); } public void teleopInit() { //_pod1.initSmartDashboard(); _pod1.setTurningSetpoint(180); _pod2.setTurningSetpoint(180); _pod3.setTurningSetpoint(180); _pod4.setTurningSetpoint(180); } public void testInit() { //Not using test since it overrides SmartDashboard display } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { //_pod1.updateSmartDashboard(); // Test turning // if (_joystick.getRawButton(1)) { _scopeTrigger.set(true); _pod1.setTurningSetpoint(90); } else if (_joystick.getRawButton(2)) { _scopeTrigger.set(true); _pod1.setTurningSetpoint(90); _pod2.setTurningSetpoint(90); _pod3.setTurningSetpoint(90); _pod4.setTurningSetpoint(90); } else if (_joystick.getRawButton(3)) { _scopeTrigger.set(true); _pod3.setTurningSetpoint(90); } else if (_joystick.getRawButton(4)) { _scopeTrigger.set(true); _pod1.setTurningSetpoint(_joystick.getDirectionDegrees() + 180.0); _pod2.setTurningSetpoint(_joystick.getDirectionDegrees() + 180.0); _pod3.setTurningSetpoint(_joystick.getDirectionDegrees() + 180.0); _pod4.setTurningSetpoint(_joystick.getDirectionDegrees() + 180.0); } else { _scopeTrigger.set(false); _pod1.setTurningSetpoint(180); _pod2.setTurningSetpoint(180); _pod3.setTurningSetpoint(180); _pod4.setTurningSetpoint(180); } } /** * This function is called periodically during test mode */ public void testPeriodic() { } public void disabledInit() { //_pod1.disable(); } public void disabledPeriodic() { } }
package com.intellij.ide.scopeView; import com.intellij.ProjectTopics; import com.intellij.ide.CopyPasteManagerEx; import com.intellij.ide.DeleteProvider; import com.intellij.ide.IdeBundle; import com.intellij.ide.IdeView; import com.intellij.ide.projectView.ProjectView; import com.intellij.ide.projectView.impl.AbstractProjectViewPane; import com.intellij.ide.projectView.impl.ModuleGroup; import com.intellij.ide.util.DeleteHandler; import com.intellij.ide.util.EditorHelper; import com.intellij.ide.util.PackageUtil; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.DataConstants; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.localVcs.LvcsAction; import com.intellij.openapi.localVcs.impl.LvcsIntegration; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.roots.ui.configuration.actions.ModuleDeleteProvider; import com.intellij.openapi.util.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.packageDependencies.DependencyValidationManager; import com.intellij.packageDependencies.ui.*; import com.intellij.problems.WolfTheProblemSolver; import com.intellij.psi.*; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.psi.search.scope.packageSet.NamedScopesHolder; import com.intellij.psi.search.scope.packageSet.PackageSet; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.TreeToolTipHandler; import com.intellij.util.EditSourceOnDoubleClickHandler; import com.intellij.util.Function; import com.intellij.util.containers.HashSet; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.ui.Tree; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.UiNotifyConnector; import com.intellij.util.ui.update.Update; import org.jdom.Element; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; public class ScopeTreeViewPanel extends JPanel implements JDOMExternalizable, Disposable { private static final Logger LOG = Logger.getInstance("com.intellij.ide.scopeView.ScopeTreeViewPanel"); private IdeView myIdeView = new MyIdeView(); private MyPsiTreeChangeAdapter myPsiTreeChangeAdapter = new MyPsiTreeChangeAdapter(); private Tree myTree = new Tree(); private final Project myProject; private TreeModelBuilder myBuilder; @SuppressWarnings({"WeakerAccess"}) public String CURRENT_SCOPE_NAME; private boolean myInitialized = false; private TreeExpansionMonitor myTreeExpansionMonitor; private CopyPasteManagerEx.CopyPasteDelegator myCopyPasteDelegator; private final MyDeletePSIElementProvider myDeletePSIElementProvider = new MyDeletePSIElementProvider(); private final ModuleDeleteProvider myDeleteModuleProvider = new ModuleDeleteProvider(); private final DependencyValidationManager myDependencyValidationManager; private WolfTheProblemSolver.ProblemListener myProblemListener = new MyProblemListener(); private MergingUpdateQueue myUpdateQueue = new MergingUpdateQueue("ScopeViewUpdate", 300, myTree.isShowing(), myTree); public ScopeTreeViewPanel(final Project project) { super(new BorderLayout()); myProject = project; initTree(); add(new JScrollPane(myTree), BorderLayout.CENTER); myDependencyValidationManager = DependencyValidationManager.getInstance(myProject); final UiNotifyConnector uiNotifyConnector = new UiNotifyConnector(myTree, myUpdateQueue); Disposer.register(this, myUpdateQueue); Disposer.register(this, uiNotifyConnector); } public void initListeners(){ myInitialized = true; final MessageBusConnection connection = myProject.getMessageBus().connect(this); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new MyModuleRootListener()); PsiManager.getInstance(myProject).addPsiTreeChangeListener(myPsiTreeChangeAdapter); WolfTheProblemSolver.getInstance(myProject).addProblemListener(myProblemListener); } public void dispose(){ PsiManager.getInstance(myProject).removePsiTreeChangeListener(myPsiTreeChangeAdapter); WolfTheProblemSolver.getInstance(myProject).removeProblemListener(myProblemListener); } public boolean isInitialized() { return myInitialized; } @Nullable public PackageDependenciesNode findNode(PsiFile file) { return myBuilder.findNode(file); } public void selectScope(final NamedScope scope) { refreshScope(scope, true); if (scope != myDependencyValidationManager.getProjectScope()) { CURRENT_SCOPE_NAME = scope.getName(); } } public void selectCurrentScope() { refreshScope(getCurrentScope(), true); } public JPanel getPanel() { return this; } private void initTree() { myTree.setCellRenderer(new MyTreeCellRenderer()); myTree.setRootVisible(false); myTree.setShowsRootHandles(true); UIUtil.setLineStyleAngled(myTree); TreeToolTipHandler.install(myTree); TreeUtil.installActions(myTree); EditSourceOnDoubleClickHandler.install(myTree); myCopyPasteDelegator = new CopyPasteManagerEx.CopyPasteDelegator(myProject, this) { protected PsiElement[] getSelectedElements() { return getSelectedPsiElements(); } }; myTreeExpansionMonitor = TreeExpansionMonitor.install(myTree, myProject); myTree.addTreeWillExpandListener(new ScopeTreeViewExpander(myTree, myProject)); } private PsiElement[] getSelectedPsiElements() { final TreePath[] treePaths = myTree.getSelectionPaths(); if (treePaths != null){ Set<PsiElement> result = new HashSet<PsiElement>(); for (TreePath path : treePaths) { PackageDependenciesNode node = (PackageDependenciesNode)path.getLastPathComponent(); final PsiElement psiElement = node.getPsiElement(); if (psiElement != null && psiElement.isValid()){ result.add(psiElement); } } return result.toArray(new PsiElement[result.size()]); } return PsiElement.EMPTY_ARRAY; } private void refreshScope(@Nullable NamedScope scope, boolean showProgress) { myTreeExpansionMonitor.freeze(); if (scope == null || scope.getValue() == null) { //was deleted scope = myDependencyValidationManager.getProjectScope(); } LOG.assertTrue(scope != null); final NamedScopesHolder holder = NamedScopesHolder.getHolder(myProject, scope.getName(), myDependencyValidationManager); final PackageSet packageSet = scope.getValue(); final DependenciesPanel.DependencyPanelSettings settings = new DependenciesPanel.DependencyPanelSettings(); settings.UI_FILTER_LEGALS = true; settings.UI_GROUP_BY_SCOPE_TYPE = false; settings.UI_SHOW_FILES = true; settings.UI_GROUP_BY_FILES = true; final ProjectView projectView = ProjectView.getInstance(myProject); settings.UI_FLATTEN_PACKAGES = projectView.isFlattenPackages(ScopeViewPane.ID); settings.UI_COMPACT_EMPTY_MIDDLE_PACKAGES = projectView.isHideEmptyMiddlePackages(ScopeViewPane.ID); myBuilder = new TreeModelBuilder(myProject, false, new TreeModelBuilder.Marker() { public boolean isMarked(PsiFile file) { return packageSet.contains(file, holder); } }, settings); myTree.setModel(myBuilder.build(myProject, showProgress)); ((DefaultTreeModel)myTree.getModel()).reload(); myTreeExpansionMonitor.restore(); } public void readExternal(Element element) throws InvalidDataException { DefaultJDOMExternalizer.readExternal(this, element); } public void writeExternal(Element element) throws WriteExternalException { DefaultJDOMExternalizer.writeExternal(this, element); } private NamedScope getCurrentScope() { NamedScope scope = NamedScopesHolder.getScope(myProject, CURRENT_SCOPE_NAME); if (scope == null) { scope = myDependencyValidationManager.getProjectScope(); } LOG.assertTrue(scope != null); return scope; } @Nullable public Object getData(String dataId) { if (dataId.equals(DataConstants.MODULE_CONTEXT)){ final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null){ PackageDependenciesNode node = (PackageDependenciesNode)selectionPath.getLastPathComponent(); if (node instanceof ModuleNode){ return ((ModuleNode)node).getModule(); } } } if (dataId.equals(DataConstants.PSI_ELEMENT)){ final TreePath selectionPath = myTree.getSelectionPath(); if (selectionPath != null){ PackageDependenciesNode node = (PackageDependenciesNode)selectionPath.getLastPathComponent(); return node != null ? node.getPsiElement() : null; } } final TreePath[] treePaths = myTree.getSelectionPaths(); if (treePaths != null){ if (dataId.equals(DataConstants.PSI_ELEMENT_ARRAY)) { Set<PsiElement> psiElements = new HashSet<PsiElement>(); for (TreePath treePath : treePaths) { final PackageDependenciesNode node = (PackageDependenciesNode)treePath.getLastPathComponent(); final PsiElement psiElement = node.getPsiElement(); if (psiElement != null){ psiElements.add(psiElement); } } return psiElements.isEmpty() ? null : psiElements.toArray(new PsiElement[psiElements.size()]); } } if (dataId.equals(DataConstants.IDE_VIEW)){ return myIdeView; } if (DataConstants.CUT_PROVIDER.equals(dataId)) { return myCopyPasteDelegator.getCutProvider(); } if (DataConstants.COPY_PROVIDER.equals(dataId)) { return myCopyPasteDelegator.getCopyProvider(); } if (DataConstants.PASTE_PROVIDER.equals(dataId)) { return myCopyPasteDelegator.getPasteProvider(); } if (DataConstants.DELETE_ELEMENT_PROVIDER.equals(dataId)) { if (getSelectedModules() != null){ return myDeleteModuleProvider; } if (getSelectedPsiElements() != null){ return myDeletePSIElementProvider; } } return null; } @Nullable private Module[] getSelectedModules(){ final TreePath[] treePaths = myTree.getSelectionPaths(); if (treePaths != null){ Set<Module> result = new HashSet<Module>(); for (TreePath path : treePaths) { PackageDependenciesNode node = (PackageDependenciesNode)path.getLastPathComponent(); if (node instanceof ModuleNode){ result.add(((ModuleNode)node).getModule()); } else if (node instanceof ModuleGroupNode){ final ModuleGroupNode groupNode = (ModuleGroupNode)node; final ModuleGroup moduleGroup = groupNode.getModuleGroup(); result.addAll(moduleGroup.modulesInGroup(myProject, true)); } } return result.isEmpty() ? null : result.toArray(new Module[result.size()]); } return null; } private void reload(final DefaultMutableTreeNode rootToReload) { final DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel(); if (rootToReload != null) { TreeUtil.sort(rootToReload, new DependencyNodeComparator()); collapseExpand(rootToReload); } else { TreeUtil.sort(treeModel, new DependencyNodeComparator()); treeModel.reload(); } } private static class MyTreeCellRenderer extends ColoredTreeCellRenderer { public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof PackageDependenciesNode) { PackageDependenciesNode node = (PackageDependenciesNode)value; if (expanded) { setIcon(node.getOpenIcon()); } else { setIcon(node.getClosedIcon()); } final SimpleTextAttributes regularAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; TextAttributes textAttributes = null; final String text = node.toString(); if (text != null) { final PsiElement psiElement = node.getPsiElement(); if (psiElement instanceof PsiDocCommentOwner && ((PsiDocCommentOwner)psiElement).isDeprecated()){ textAttributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.DEPRECATED_ATTRIBUTES).clone(); } if (textAttributes == null){ textAttributes = regularAttributes.toTextAttributes(); } textAttributes.setForegroundColor(node.getStatus().getColor()); append(text, SimpleTextAttributes.fromTextAttributes(textAttributes)); } } } } private class MyPsiTreeChangeAdapter extends PsiTreeChangeAdapter { public void childAdded(final PsiTreeChangeEvent event) { final PsiElement element = event.getParent(); final PsiElement child = event.getChild(); if (child == null) return; if (element instanceof PsiDirectory || element instanceof PsiPackage) { queueUpdate(new Runnable(){ public void run() { if (myProject.isDisposed()) return; myTreeExpansionMonitor.freeze(); if (!child.isValid()) return; processNodeCreation(child); myTreeExpansionMonitor.restore(); } }, false); } } private void processNodeCreation(final PsiElement psiElement) { if (psiElement instanceof PsiFile) { reload(myBuilder.addFileNode((PsiFile)psiElement)); } else if (psiElement instanceof PsiDirectory) { final PsiElement[] children = psiElement.getChildren(); for (PsiElement child : children) { processNodeCreation(child); } } } public void beforeChildRemoval(final PsiTreeChangeEvent event) { final PsiElement child = event.getChild(); final PsiElement parent = event.getParent(); if (parent instanceof PsiDirectory && (child instanceof PsiFile || child instanceof PsiDirectory)) { queueUpdate(new Runnable() { public void run() { if (myProject.isDisposed()) return; myTreeExpansionMonitor.freeze(); collapseExpand(myBuilder.removeNode(child, (PsiDirectory)parent)); myTreeExpansionMonitor.restore(); } }, true); } } public void childMoved(PsiTreeChangeEvent event) { final PsiElement oldParent = event.getOldParent(); final PsiElement newParent = event.getNewParent(); final PsiElement child = event.getChild(); if (oldParent instanceof PsiDirectory && newParent instanceof PsiDirectory) { if (child instanceof PsiFile) { queueUpdate(new Runnable() { public void run() { if (myProject.isDisposed()) return; myTreeExpansionMonitor.freeze(); if (child.isValid()) { collapseExpand(myBuilder.removeNode(child, (PsiDirectory)oldParent)); collapseExpand(myBuilder.addFileNode((PsiFile)child)); } myTreeExpansionMonitor.restore(); } }, true); } } } public void childrenChanged(PsiTreeChangeEvent event) { final PsiElement parent = event.getParent(); final PsiFile file = parent.getContainingFile(); if (file instanceof PsiJavaFile) { if (!file.getViewProvider().isPhysical()) return; queueUpdate(new Runnable() { public void run() { if (myProject.isDisposed()) return; myTreeExpansionMonitor.freeze(); if (file.isValid()) { collapseExpand(myBuilder.getFileParentNode(file)); } myTreeExpansionMonitor.restore(); } }, false); } } private void queueUpdate(final Runnable request, boolean updateImmediately) { if (updateImmediately && myTree.isShowing()) { myUpdateQueue.run(new Update(request) { public void run() { request.run(); } }); } else { myUpdateQueue.queue(new Update(request) { public void run() { request.run(); } public boolean isExpired() { return !myTree.isShowing(); } }); } } } private void collapseExpand(DefaultMutableTreeNode node){ if (node == null) return; ((DefaultTreeModel)myTree.getModel()).reload(node); TreePath path = new TreePath(node.getPath()); if (!myTree.isCollapsed(path)){ myTree.collapsePath(path); myTree.expandPath(path); TreeUtil.sort(node, new DependencyNodeComparator()); } } private class MyModuleRootListener implements ModuleRootListener { public void beforeRootsChange(ModuleRootEvent event) { } public void rootsChanged(ModuleRootEvent event) { myUpdateQueue.cancelAllUpdates(); myUpdateQueue.queue(new Update("RootsChanged") { public void run() { refreshScope(getCurrentScope(), false); } public boolean isExpired() { return !myTree.isShowing(); } }); } } private class MyIdeView implements IdeView { public void selectElement(final PsiElement element) { if (element != null) { final boolean isDirectory = element instanceof PsiDirectory; if (!isDirectory) { Editor editor = EditorHelper.openInEditor(element); if (editor != null) { ToolWindowManager.getInstance(myProject).activateEditorComponent(); } } } } @Nullable private PsiDirectory getDirectory() { final TreePath[] selectedPaths = myTree.getSelectionPaths(); if (selectedPaths != null) { if (selectedPaths.length != 1) return null; TreePath path = selectedPaths[0]; final PackageDependenciesNode node = (PackageDependenciesNode)path.getLastPathComponent(); if (node instanceof DirectoryNode) { DirectoryNode directoryNode = (DirectoryNode)node; while (directoryNode.getCompactedDirNode() != null){ directoryNode = directoryNode.getCompactedDirNode(); LOG.assertTrue(directoryNode != null); } return (PsiDirectory)directoryNode.getPsiElement(); } else if (node instanceof ClassNode) { final PsiElement psiClass = node.getPsiElement(); LOG.assertTrue(psiClass != null); final PsiFile psiFile = psiClass.getContainingFile(); LOG.assertTrue(psiFile != null); return psiFile.getContainingDirectory(); } else if (node instanceof FileNode) { final PsiFile psiFile = (PsiFile)node.getPsiElement(); LOG.assertTrue(psiFile != null); return psiFile.getContainingDirectory(); } } return null; } public PsiDirectory[] getDirectories() { PsiDirectory directory = getDirectory(); return directory == null ? PsiDirectory.EMPTY_ARRAY : new PsiDirectory[]{directory}; } @Nullable public PsiDirectory getOrChooseDirectory() { return PackageUtil.getOrChooseDirectory(this); } } private final class MyDeletePSIElementProvider implements DeleteProvider { public boolean canDeleteElement(DataContext dataContext) { final PsiElement[] elements = getSelectedPsiElements(); return DeleteHandler.shouldEnableDeleteAction(elements); } public void deleteElement(DataContext dataContext) { List<PsiElement> allElements = Arrays.asList(getSelectedPsiElements()); ArrayList<PsiElement> validElements = new ArrayList<PsiElement>(); for (PsiElement psiElement : allElements) { if (psiElement != null && psiElement.isValid()) validElements.add(psiElement); } final PsiElement[] elements = validElements.toArray(new PsiElement[validElements.size()]); LvcsAction action = LvcsIntegration.checkinFilesBeforeRefactoring(myProject, IdeBundle.message("progress.deleting")); try { DeleteHandler.deletePsiElement(elements, myProject); } finally { LvcsIntegration.checkinFilesAfterRefactoring(myProject, action); } } } public JTree getTree() { return myTree; } private class MyProblemListener extends WolfTheProblemSolver.ProblemListener { public void problemsAppeared(VirtualFile file) { queueUpdate(file, new Function<PsiFile, DefaultMutableTreeNode>() { @Nullable public DefaultMutableTreeNode fun(final PsiFile psiFile) { return myBuilder.addFileNode(psiFile); } }); } public void problemsDisappeared(VirtualFile file) { queueUpdate(file, new Function<PsiFile, DefaultMutableTreeNode>() { @Nullable public DefaultMutableTreeNode fun(final PsiFile psiFile) { return myBuilder.removeNode(psiFile, psiFile.getContainingDirectory()); } }); } private void queueUpdate(final VirtualFile fileToRefresh, final Function<PsiFile, DefaultMutableTreeNode> rootToReloadGetter) { AbstractProjectViewPane pane = ProjectView.getInstance(myProject).getCurrentProjectViewPane(); if (pane == null || !ScopeViewPane.ID.equals(pane.getId()) || !DependencyValidationManager.getInstance(myProject).getProblemsScope().getName().equals(pane.getSubId())) { return; } myUpdateQueue.queue(new Update(fileToRefresh) { public void run() { if (myProject.isDisposed()) return; myTreeExpansionMonitor.freeze(); final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(fileToRefresh); if (psiFile != null) { reload(rootToReloadGetter.fun(psiFile)); } myTreeExpansionMonitor.restore(); } public boolean isExpired() { return !myTree.isShowing(); } }); } } }
package org.freecompany.redline.payload; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.logging.Logger; import org.freecompany.redline.ChannelWrapper.Key; import org.freecompany.redline.ReadableChannelWrapper; import org.freecompany.redline.Util; import static java.util.Arrays.asList; import static java.util.logging.Level.FINE; import static java.util.logging.Logger.getLogger; import static org.freecompany.redline.Util.normalizePath; import static org.freecompany.redline.payload.CpioHeader.DEFAULT_DIRECTORY_PERMISSION; import static org.freecompany.redline.payload.CpioHeader.DIR; import static org.freecompany.redline.payload.CpioHeader.FILE; import static org.freecompany.redline.payload.CpioHeader.SYMLINK; /** * The contents of an RPM archive. These entries define the files and links that * the RPM contains as well as headers those files require. Note that the RPM format * requires that files in the archive be naturally ordered. */ public class Contents { private static final Set< String> builtin = new HashSet< String>(); private static final Set< String> docDirs = new HashSet< String>(); static { builtin.add( "/"); builtin.add( "/bin"); builtin.add( "/dev"); builtin.add( "/etc"); builtin.add( "/lib"); builtin.add( "/usr"); builtin.add( "/usr/bin"); builtin.add( "/usr/lib"); builtin.add( "/usr/local"); builtin.add( "/usr/local/bin"); builtin.add( "/usr/local/lib"); builtin.add( "/usr/sbin"); builtin.add( "/usr/share"); builtin.add( "/sbin"); builtin.add( "/opt"); builtin.add( "/tmp"); builtin.add( "/var"); builtin.add( "/var/log"); docDirs.add( "/usr/doc"); docDirs.add( "/usr/man"); docDirs.add( "/usr/X11R6/man"); docDirs.add( "/usr/share/doc"); docDirs.add( "/usr/share/man"); docDirs.add( "/usr/share/info"); } private Logger logger = getLogger( Contents.class.getName()); private int inode = 1; protected final TreeSet< CpioHeader> headers = new TreeSet< CpioHeader>( new HeaderComparator()); protected final HashSet< String> files = new HashSet< String>(); protected final HashMap< CpioHeader, Object> sources = new HashMap< CpioHeader, Object>(); public synchronized void addLink( final String path, final String target) { addLink( path, target, -1); } public synchronized void addLink( String path, final String target, int permissions) { if ( files.contains( path)) return; files.add( path); logger.log( FINE, "Adding link ''{0}''.", path); CpioHeader header = new CpioHeader( path); header.setType( SYMLINK); header.setFileSize( target.length()); header.setMtime( System.currentTimeMillis()); if ( permissions != -1) header.setPermissions( permissions); headers.add( header); sources.put( header, target); } public synchronized void addDirectory( final String path) { addDirectory( path, -1); } public synchronized void addDirectory( final String path, final Directive directive) { addDirectory( path, -1, directive, null, null); } public synchronized void addDirectory( final String path, final int permissions) { addDirectory(path, permissions, null, null, null); } public synchronized void addDirectory( final String path, final int permissions, final Directive directive, final String uname, final String gname) { addDirectory(path, permissions, directive, uname, gname, true); } public synchronized void addDirectory( final String path, final int permissions, final Directive directive, final String uname, final String gname, boolean addParents) { if ( files.contains( path)) return; if ( addParents) addParents( new File( path), permissions, uname, gname); files.add( path); logger.log( FINE, "Adding directory ''{0}''.", path); CpioHeader header = new CpioHeader( path); header.setType( DIR); header.setInode( inode++); if (uname != null) header.setUname(uname); if (gname != null) header.setGname(gname); header.setMtime( System.currentTimeMillis()); if ( permissions != -1) header.setPermissions( permissions); else header.setPermissions( DEFAULT_DIRECTORY_PERMISSION); headers.add( header); sources.put( header, null); if ( directive != null) header.setFlags( directive.flag()); } public synchronized void addFile( final String path, final File source) throws FileNotFoundException { addFile( path, source, -1); } public synchronized void addFile( final String path, final File source, int permissions) throws FileNotFoundException { addFile(path, source, permissions, null, null, null); } public synchronized void addFile( final String path, final File source, int permissions, final Directive directive) throws FileNotFoundException { addFile(path, source, permissions, null, null, null); } public synchronized void addFile( final String path, final File source, final int permissions, final Directive directive, final String uname, final String gname) throws FileNotFoundException { if ( files.contains( path)) return; addParents( new File( path), permissions, uname, gname); files.add( path); logger.log( FINE, "Adding file ''{0}''.", path); CpioHeader header = new CpioHeader( path, source); header.setType( FILE); header.setInode( inode++); if (uname != null) header.setUname(uname); if (gname != null) header.setGname(gname); if ( permissions != -1) header.setPermissions( permissions); headers.add( header); sources.put( header, source); if ( directive != null) header.setFlags( directive.flag()); } /** * Adds entries for parent directories of this file, so that they may be cleaned up when * removing the package. */ protected synchronized void addParents( final File file, final int permissions, final String uname, final String gname ) { final ArrayList< String> parents = new ArrayList< String>(); listParents( parents, file); for ( String parent : parents) addDirectory( parent, permissions, null, uname, gname); } /** * Retrieve the size of this archive in number of files. This count includes both directory entries and * soft links. */ public int size() { return headers.size(); } /** * Retrieve the archive headers. The returned {@link Iterable} will iterate in the correct order for * the final archive. */ public Iterable< CpioHeader> headers() { return headers; } /** * Retrieves the content for this archive entry, which may be a {@link File} if the entry is a regular file or * a {@link CharSequence} containing the name of the target path if the entry is a link. This is the value to * be written to the archive as the body of the entry. */ public Object getSource( CpioHeader header) { return sources.get( header); } /** * Accumulated size of all files included in the archive. */ public int getTotalSize() { int total = 0; for ( Object object : sources.values()) if ( object instanceof File) total += (( File) object).length(); return total; } /** * Gets the dirnames headers values. */ public String[] getDirNames() { final Set< String> set = new LinkedHashSet< String>(); for ( CpioHeader header : headers) { String path = new File( header.getName()).getParent(); if ( path == null) continue; String parent = normalizePath( path); if ( !parent.endsWith( "/")) parent += "/"; set.add( parent); } return set.toArray( new String[ set.size()]); } /** * Gets the dirindexes headers values. */ // TODO: Fix this (as part of general refactoring) to be much better. public int[] getDirIndexes() { final List< String> dirs = asList( getDirNames()); int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) { String path = new File( header.getName()).getParent(); if ( path == null) continue; String parent = normalizePath( path); if ( !parent.endsWith( "/")) parent += "/"; array[ x++] = dirs.indexOf( parent); } return array; } /** * Gets the basenames header values. */ public String[] getBaseNames() { String[] array = new String[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = normalizePath( new File( header.getName()).getName()); return array; } /** * Gets the sizes header values. */ public int[] getSizes() { int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) { Object object = sources.get( header); if ( object instanceof File) array[ x] = ( int) (( File) object).length(); else if ( header.getType() == DIR) array[ x] = 4096; ++x; } return array; } /** * Gets the modes header values. */ public short[] getModes() { short[] array = new short[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = ( short) header.getMode(); return array; } /** * Gets the rdevs header values. */ public short[] getRdevs() { short[] array = new short[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = ( short) (( header.getRdevMajor() << 8) + header.getRdevMinor()); return array; } /** * Gets the mtimes header values. */ public int[] getMtimes() { int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) { array[ x++] = ( int) header.getMtime(); } return array; } /** * Caclulates an MD5 hash for each file in the archive. */ public String[] getMD5s() throws FileNotFoundException, NoSuchAlgorithmException, IOException { /** * This could be more efficiently handled during the output phase using a filtering channel, * but would require placeholder values in the archive and some state. This is left for a * later refactoring. */ final ByteBuffer buffer = ByteBuffer.allocate( 4096); String[] array = new String[ headers.size()]; int x = 0; for ( CpioHeader header : headers) { Object object = sources.get( header); String value = ""; if ( object instanceof File) { final ReadableChannelWrapper input = new ReadableChannelWrapper( new FileInputStream(( File) object).getChannel()); final Key< byte[]> key = input.start( "MD5"); while ( input.read( buffer) != -1) buffer.rewind(); value = new String( Util.hex( input.finish( key))); input.close(); } array[ x++] = value; } return array; } /** * Gets the linktos header values. */ public String[] getLinkTos() { String[] array = new String[ headers.size()]; int x = 0; for ( CpioHeader header : headers) { Object object = sources.get( header); String value = ""; if ( object instanceof String) value = String.valueOf( object); array[ x++] = value; } return array; } /** * Gets the flags header values. */ public int[] getFlags() { int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = header.getFlags(); return array; } /** * Gets the users header values. */ public String[] getUsers() { String[] array = new String[ headers.size()]; int x = 0; for (CpioHeader header : headers) { array[ x++] = header.getUname() == null ? "root" : header.getUname(); } return array; } /** * Gets the groups header values. */ public String[] getGroups() { String[] array = new String[ headers.size()]; int x = 0; for (CpioHeader header : headers) { array[ x++] = header.getGname() == null ? "root" : header.getGname(); } return array; } /** * Gets the colors header values. */ public int[] getColors() { return new int[ headers.size()]; } /** * Gets the verifyflags header values. */ public int[] getVerifyFlags() { int[] array = new int[ headers.size()]; Arrays.fill( array, -1); return array; } /** * Gets the classes header values. */ public int[] getClasses() { int[] array = new int[ headers.size()]; Arrays.fill( array, 1); return array; } /** * Gets the devices header values. */ public int[] getDevices() { int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = ( header.getDevMajor() << 8) + header.getDevMinor(); return array; } /** * Gets the inodes header values. */ public int[] getInodes() { int[] array = new int[ headers.size()]; int x = 0; for ( CpioHeader header : headers) array[ x++] = ( int) header.getInode(); return array; } /** * Gets the langs header values. */ public String[] getLangs() { String[] array = new String[ headers.size()]; Arrays.fill( array, ""); return array; } /** * Gets the dependsx header values. */ public int[] getDependsX() { return new int[ headers.size()]; } /** * Gets the dependsn header values. */ public int[] getDependsN() { return new int[ headers.size()]; } /** * Gets the contexts header values. */ public String[] getContexts() { String[] array = new String[ headers.size()]; Arrays.fill( array, "<<none>>"); return array; } /** * Generates a list of parent paths given a starting path. */ protected static void listParents( final List< String> parents, final File file) { final File parent = file.getParentFile(); if ( parent == null) return; final String path = normalizePath( parent.getPath()); if ( builtin.contains( path)) return; parents.add( path); listParents( parents, parent); } /** * Comparator that orders files in the CPIO archive by their file name * as present in th header. */ private static class HeaderComparator implements Comparator< CpioHeader> { public int compare( final CpioHeader one, final CpioHeader two) { return one.getName().compareTo( two.getName()); } public boolean equals( final CpioHeader one, final CpioHeader two) { return one.getName().equals( two.getName()); } }; }
package net.fortuna.ical4j.model; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import net.fortuna.ical4j.model.parameter.AltRep; import net.fortuna.ical4j.model.parameter.Cn; import net.fortuna.ical4j.model.parameter.CuType; import net.fortuna.ical4j.model.parameter.DelegatedFrom; import net.fortuna.ical4j.model.parameter.DelegatedTo; import net.fortuna.ical4j.model.parameter.Dir; import net.fortuna.ical4j.model.parameter.Encoding; import net.fortuna.ical4j.model.parameter.FbType; import net.fortuna.ical4j.model.parameter.FmtType; import net.fortuna.ical4j.model.parameter.Language; import net.fortuna.ical4j.model.parameter.Member; import net.fortuna.ical4j.model.parameter.PartStat; import net.fortuna.ical4j.model.parameter.Range; import net.fortuna.ical4j.model.parameter.RelType; import net.fortuna.ical4j.model.parameter.Related; import net.fortuna.ical4j.model.parameter.Role; import net.fortuna.ical4j.model.parameter.Rsvp; import net.fortuna.ical4j.model.parameter.SentBy; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.parameter.Value; import net.fortuna.ical4j.model.parameter.XParameter; /** * A factory for creating iCalendar parameters. * * @author Ben Fortuna */ public final class ParameterFactoryImpl implements ParameterFactory { private static ParameterFactoryImpl instance = new ParameterFactoryImpl(); private Map factories; /** * Constructor made private to prevent instantiation. */ private ParameterFactoryImpl() { factories = new HashMap(); factories.put(Parameter.ALTREP, createAltRepFactory()); factories.put(Parameter.CN, createCnFactory()); factories.put(Parameter.CUTYPE, createCuTypeFactory()); factories.put(Parameter.DELEGATED_FROM, createDelegatedFromFactory()); factories.put(Parameter.DELEGATED_TO, createDelegatedToFactory()); factories.put(Parameter.DIR, createDirFactory()); factories.put(Parameter.ENCODING, createEncodingFactory()); factories.put(Parameter.FMTTYPE, createFmtTypeFactory()); factories.put(Parameter.FBTYPE, createFbTypeFactory()); factories.put(Parameter.LANGUAGE, createLanguageFactory()); factories.put(Parameter.MEMBER, createMemberFactory()); factories.put(Parameter.PARTSTAT, createPartStatFactory()); factories.put(Parameter.RANGE, createRangeFactory()); factories.put(Parameter.RELATED, createRelatedFactory()); factories.put(Parameter.RELTYPE, createRelTypeFactory()); factories.put(Parameter.ROLE, createRoleFactory()); factories.put(Parameter.RSVP, createRsvpFactory()); factories.put(Parameter.SENT_BY, createSentByFactory()); factories.put(Parameter.TZID, createTzIdFactory()); factories.put(Parameter.VALUE, createValueFactory()); } /** * @return */ private ParameterFactory createAltRepFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new AltRep(value); } }; } /** * @return */ private ParameterFactory createCnFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Cn(value); } }; } /** * @return */ private ParameterFactory createCuTypeFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { CuType parameter = new CuType(value); if (CuType.INDIVIDUAL.equals(parameter)) { return CuType.INDIVIDUAL; } else if (CuType.GROUP.equals(parameter)) { return CuType.GROUP; } else if (CuType.RESOURCE.equals(parameter)) { return CuType.RESOURCE; } else if (CuType.ROOM.equals(parameter)) { return CuType.ROOM; } else if (CuType.UNKNOWN.equals(parameter)) { return CuType.UNKNOWN; } return parameter; } }; } /** * @return */ private ParameterFactory createDelegatedFromFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new DelegatedFrom(value); } }; } /** * @return */ private ParameterFactory createDelegatedToFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new DelegatedTo(value); } }; } /** * @return */ private ParameterFactory createDirFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Dir(value); } }; } /** * @return */ private ParameterFactory createEncodingFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Encoding parameter = new Encoding(value); if (Encoding.EIGHT_BIT.equals(parameter)) { return Encoding.EIGHT_BIT; } else if (Encoding.BASE64.equals(parameter)) { return Encoding.BASE64; } return parameter; } }; } /** * @return */ private ParameterFactory createFmtTypeFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new FmtType(value); } }; } /** * @return */ private ParameterFactory createFbTypeFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { FbType parameter = new FbType(value); if (FbType.FREE.equals(parameter)) { return FbType.FREE; } else if (FbType.BUSY.equals(parameter)) { return FbType.BUSY; } else if (FbType.BUSY_TENTATIVE.equals(parameter)) { return FbType.BUSY_TENTATIVE; } else if (FbType.BUSY_UNAVAILABLE.equals(parameter)) { return FbType.BUSY_UNAVAILABLE; } return parameter; } }; } /** * @return */ private ParameterFactory createLanguageFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Language(value); } }; } /** * @return */ private ParameterFactory createMemberFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new Member(value); } }; } /** * @return */ private ParameterFactory createPartStatFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { PartStat parameter = new PartStat(value); if (PartStat.NEEDS_ACTION.equals(parameter)) { return PartStat.NEEDS_ACTION; } else if (PartStat.ACCEPTED.equals(parameter)) { return PartStat.ACCEPTED; } else if (PartStat.DECLINED.equals(parameter)) { return PartStat.DECLINED; } else if (PartStat.TENTATIVE.equals(parameter)) { return PartStat.TENTATIVE; } else if (PartStat.DELEGATED.equals(parameter)) { return PartStat.DELEGATED; } else if (PartStat.COMPLETED.equals(parameter)) { return PartStat.COMPLETED; } else if (PartStat.IN_PROCESS.equals(parameter)) { return PartStat.IN_PROCESS; } return parameter; } }; } /** * @return */ private ParameterFactory createRangeFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Range parameter = new Range(value); if (Range.THISANDFUTURE.equals(parameter)) { return Range.THISANDFUTURE; } else if (Range.THISANDPRIOR.equals(parameter)) { return Range.THISANDPRIOR; } return parameter; } }; } /** * @return */ private ParameterFactory createRelatedFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Related parameter = new Related(value); if (Related.START.equals(parameter)) { return Related.START; } else if (Related.END.equals(parameter)) { return Related.END; } return parameter; } }; } /** * @return */ private ParameterFactory createRelTypeFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { RelType parameter = new RelType(value); if (RelType.PARENT.equals(parameter)) { return RelType.PARENT; } else if (RelType.CHILD.equals(parameter)) { return RelType.CHILD; } if (RelType.SIBLING.equals(parameter)) { return RelType.SIBLING; } return parameter; } }; } /** * @return */ private ParameterFactory createRoleFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Role parameter = new Role(value); if (Role.CHAIR.equals(parameter)) { return Role.CHAIR; } else if (Role.REQ_PARTICIPANT.equals(parameter)) { return Role.REQ_PARTICIPANT; } else if (Role.OPT_PARTICIPANT.equals(parameter)) { return Role.OPT_PARTICIPANT; } else if (Role.NON_PARTICIPANT.equals(parameter)) { return Role.NON_PARTICIPANT; } return parameter; } }; } /** * @return */ private ParameterFactory createRsvpFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Rsvp parameter = new Rsvp(value); if (Rsvp.TRUE.equals(parameter)) { return Rsvp.TRUE; } else if (Rsvp.FALSE.equals(parameter)) { return Rsvp.FALSE; } return parameter; } }; } /** * @return */ private ParameterFactory createSentByFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new SentBy(value); } }; } /** * @return */ private ParameterFactory createTzIdFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { return new TzId(value); } }; } /** * @return */ private ParameterFactory createValueFactory() { return new ParameterFactory() { /* (non-Javadoc) * @see net.fortuna.ical4j.model.ParameterFactory#createParameter(java.lang.String, java.lang.String) */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { Value parameter = new Value(value); if (Value.BINARY.equals(parameter)) { return Value.BINARY; } else if (Value.BOOLEAN.equals(parameter)) { return Value.BOOLEAN; } else if (Value.CAL_ADDRESS.equals(parameter)) { return Value.CAL_ADDRESS; } else if (Value.DATE.equals(parameter)) { return Value.DATE; } else if (Value.DATE_TIME.equals(parameter)) { return Value.DATE_TIME; } else if (Value.DURATION.equals(parameter)) { return Value.DURATION; } else if (Value.FLOAT.equals(parameter)) { return Value.FLOAT; } else if (Value.INTEGER.equals(parameter)) { return Value.INTEGER; } else if (Value.PERIOD.equals(parameter)) { return Value.PERIOD; } else if (Value.RECUR.equals(parameter)) { return Value.RECUR; } else if (Value.TEXT.equals(parameter)) { return Value.TEXT; } else if (Value.TIME.equals(parameter)) { return Value.TIME; } else if (Value.URI.equals(parameter)) { return Value.URI; } else if (Value.UTC_OFFSET.equals(parameter)) { return Value.UTC_OFFSET; } return parameter; } }; } /** * @return Returns the instance. */ public static ParameterFactoryImpl getInstance() { return instance; } /** * Creates a parameter. * * @param name * name of the parameter * @param value * a parameter value * @return a component * @throws URISyntaxException thrown when the specified string * is not a valid representation of a URI for selected parameters */ public Parameter createParameter(final String name, final String value) throws URISyntaxException { ParameterFactory factory = (ParameterFactory) factories.get(name); if (factory != null) { return factory.createParameter(name, value); } else if (isExperimentalName(name)) { return new XParameter(name, value); } else { throw new IllegalArgumentException("Invalid parameter name: " + name); } } /** * @param name * @return */ private boolean isExperimentalName(final String name) { return name.startsWith(Parameter.EXPERIMENTAL_PREFIX) && name.length() > Parameter.EXPERIMENTAL_PREFIX.length(); } }
package org.opencms.ade.galleries; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.GalleryMode; import org.opencms.main.CmsLog; import org.opencms.util.CmsRequestUtil; import org.opencms.workplace.CmsDialog; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.PageContext; import org.apache.commons.logging.Log; /** * Provides methods to open gwt-based gallery dialog.<p> * * @author Polina Smagina * @author Ruediger Kurz * * @version $Revision: 1.3 $ * * @since 8.0 */ public class CmsOpenGallery extends CmsDialog { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsOpenGallery.class); /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsOpenGallery(PageContext context, HttpServletRequest req, HttpServletResponse res) { super(context, req, res); } /** * Opens the gallery.<p> */ public void openGallery() { String galleryPath = getParamResource(); if ((galleryPath != null) && !galleryPath.endsWith("/")) { galleryPath += "/"; } Map<String, Object> params = new HashMap<String, Object>(); params.put(I_CmsGalleryProviderConstants.ReqParam.dialogmode.name(), GalleryMode.view.name()); params.put(I_CmsGalleryProviderConstants.ReqParam.gallerypath.name(), galleryPath); params.put(I_CmsGalleryProviderConstants.ReqParam.types.name(), ""); try { sendForward(I_CmsGalleryProviderConstants.VFS_OPEN_GALLERY_PATH, CmsRequestUtil.createParameterMap(params)); } catch (Exception e) { LOG.error(e); } } }
package org.opencms.gwt.client.ui; import org.opencms.gwt.client.Messages; import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Panel; /** * Provides a generic error dialog.<p> * * @author Tobias Herrmann * * @version $Revision: 1.3 $ * * @since 8.0.0 */ public class CmsErrorDialog extends CmsPopupDialog { /** The 'close' button. */ private CmsPushButton m_closeButton; private CmsFieldSet m_detailsFieldset; private HTML m_messageHtml; /** * Constructor.<p> * * @param message the error message * @param details the error details */ public CmsErrorDialog(String message, String details) { super(); setAutoHideEnabled(false); setModal(true); setGlassEnabled(true); setText(Messages.get().key(Messages.GUI_ERROR_0)); m_closeButton = new CmsPushButton(); m_closeButton.setText(Messages.get().key(Messages.GUI_OK_0)); m_closeButton.setUseMinWidth(true); m_closeButton.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ @Override public void onClick(ClickEvent event) { onClose(); } }); addButton(m_closeButton); Panel content = new FlowPanel(); m_messageHtml = createMessageHtml(message); content.add(m_messageHtml); if (details != null) { m_detailsFieldset = createDetailsFieldSet(details); content.add(m_detailsFieldset); } setContent(content); this.show(); this.center(); } /** * @see org.opencms.gwt.client.ui.CmsPopup#center() */ @Override public void center() { super.center(); onShow(); } /** * @see org.opencms.gwt.client.ui.CmsPopup#show() */ @Override public void show() { super.show(); onShow(); } /** * Executed on 'close' click. <p> */ protected void onClose() { m_closeButton.setEnabled(false); hide(); } /** * Creates a field-set containing the error details.<p> * * @param details the error details * * @return the field-set widget */ private CmsFieldSet createDetailsFieldSet(String details) { CmsFieldSet fieldset = new CmsFieldSet(); fieldset.addStyleName(I_CmsLayoutBundle.INSTANCE.errorDialogCss().details()); fieldset.setLegend(Messages.get().key(Messages.GUI_DETAILS_0)); fieldset.addContent(new HTML(details)); fieldset.setCollapsed(true); return fieldset; } /** * Creates the message HTML widget containing error icon and message.<p> * * @param message the message * * @return the HTML widget */ private HTML createMessageHtml(String message) { StringBuffer buffer = new StringBuffer(64); buffer.append("<div class=\"").append(I_CmsLayoutBundle.INSTANCE.errorDialogCss().errorIcon()).append( "\"></div><p class=\"").append(I_CmsLayoutBundle.INSTANCE.errorDialogCss().message()).append("\">").append( message).append("</p><hr class=\"").append(I_CmsLayoutBundle.INSTANCE.generalCss().clearAll()).append( "\" />"); return new HTML(buffer.toString()); } /** * Checks the available space and sets max-height to the details field-set. */ private void onShow() { int maxHeight = Window.getClientHeight() - 180 - m_messageHtml.getOffsetHeight(); if (m_detailsFieldset != null) { m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx("maxHeight", maxHeight); } } }
import java.io.FileWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.net.URL; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import com.chain.api.*; import com.chain.api.MockHsm.Key; import com.chain.http.Context; import com.chain.signing.HsmSigner; public class IouSettlement { public static void main(String[] args) throws Exception { Context ctx = new Context(new URL(System.getenv("CHAIN_API_URL"))); ctx.setConnectTimeout(10, TimeUnit.MINUTES); ctx.setReadTimeout(10, TimeUnit.MINUTES); ctx.setWriteTimeout(10, TimeUnit.MINUTES); setup(ctx); bench(ctx); System.exit(0); } static void setup(Context ctx) throws Exception { MockHsm.Key dealerAccountKey = MockHsm.Key.create(ctx); MockHsm.Key dealerIssuerKey = MockHsm.Key.create(ctx); MockHsm.Key northBankIssuerKey = MockHsm.Key.create(ctx); MockHsm.Key southBankIssuerKey = MockHsm.Key.create(ctx); loadKeys(ctx); new Asset.Builder() .setAlias("dealerusd") .addRootXpub(dealerIssuerKey.xpub) .setQuorum(1) .addTag("entity", "dealer") .addTag("currency", "usd") .create(ctx); new Asset.Builder() .setAlias("nbusd") .addRootXpub(northBankIssuerKey.xpub) .setQuorum(1) .addTag("currency", "usd") .create(ctx); new Asset.Builder() .setAlias("sbusd") .addRootXpub(southBankIssuerKey.xpub) .setQuorum(1) .addTag("currency", "usd") .create(ctx); new Account.Builder() .setAlias("dealer") .addRootXpub(dealerAccountKey.xpub) .setQuorum(1) .create(ctx); new Account.Builder().setAlias("nb").addRootXpub(dealerAccountKey.xpub).setQuorum(1).create(ctx); new Account.Builder().setAlias("sb").addRootXpub(dealerAccountKey.xpub).setQuorum(1).create(ctx); Dealer dealer = new Dealer(ctx, getAccount(ctx, "dealer"), getAsset(ctx, "dealerusd")); Bank northBank = new Bank(ctx, dealer, getAsset(ctx, "nbusd"), getAccount(ctx, "nb")); Bank southBank = new Bank(ctx, dealer, getAsset(ctx, "sbusd"), getAccount(ctx, "sb")); Corp acme = new Corp("acme", northBank, ctx); Corp zzzz = new Corp("zzzz", southBank, ctx); // Number of threads per corp. final int nthread = 20; // Create enough txs to equal (one day's worth of activity at 10 tx/s). //final int ntxTotal = 10 * 60*60*24; // should be multiple of 2*nthread final int ntxTotal = 10 * 60 * 30; // start with a half hour's worth // Number of transactions per thread. // nthread * 2 corps * ntx = ntxTotal final int ntx = ntxTotal / 2 / nthread; ExecutorService pool = Executors.newFixedThreadPool(2 * nthread); List<Callable<Integer>> x = new ArrayList<>(); for (int t = 0; t < nthread; t++) { x.add( () -> { for (int i = 0; i < ntx; i++) { if (i % 10 == 0) { System.out.printf("%d / %d (%d%%)\ntx", i, ntx, 100 * i / ntx); } Instant ti = Instant.now(); acme.pay(zzzz, i + 1); Duration elapsed = Duration.between(ti, Instant.now()); long sleep = 100 - elapsed.toMillis(); if (sleep > 0) { Thread.sleep(sleep); // offer at most 10 calls/sec. } } return 1; }); } for (int t = 0; t < nthread; t++) { x.add( () -> { for (int i = 0; i < ntx; i++) { if (i % 10 == 0) { System.out.printf("%d / %d (%d%%)\ntx", i, ntx, 100 * i / ntx); } Instant ti = Instant.now(); zzzz.pay(acme, i + 1); Duration elapsed = Duration.between(ti, Instant.now()); long sleep = 100 - elapsed.toMillis(); if (sleep > 0) { Thread.sleep(sleep); // offer at most 10 calls/sec. } } return 1; }); } List<Future<Integer>> futures = pool.invokeAll(x); for (int t = 0; t < 2 * nthread; t++) { futures.get(t).get(); } System.out.println("setup done"); } static void bench(Context ctx) throws Exception { loadKeys(ctx); Dealer dealer = new Dealer(ctx, getAccount(ctx, "dealer"), getAsset(ctx, "dealerusd")); Bank northBank = new Bank(ctx, dealer, getAsset(ctx, "nbusd"), getAccount(ctx, "nb")); Bank southBank = new Bank(ctx, dealer, getAsset(ctx, "sbusd"), getAccount(ctx, "sb")); Corp acme = new Corp("acme", northBank, ctx); Corp zzzz = new Corp("zzzz", southBank, ctx); // Target is 10 tx/s total. // We are going to do 5tx/s per corp. // We'll also do 5 threads per corp, // so each thread should do 1 tx/s. // Number of threads per corp. final int nthread = 5; // Min time (in ms) between attempts to send each transaction in a thread. final long txperiod = 1000; //final int ntxTotal = 10 * 60*60*24; // should be multiple of 2*nthread final int ntxTotal = 10 * 60 * 30; // start with a half hour's worth // Number of transactions per thread. // nthread * 2 corps * ntx = ntxTotal final int ntx = ntxTotal / 2 / nthread; ExecutorService pool = Executors.newFixedThreadPool(2 * nthread); List<Callable<Integer>> x = new ArrayList<>(); for (int t = 0; t < nthread; t++) { x.add( () -> { for (int i = 0; i < ntx; i++) { if (i % 10 == 0) { System.out.printf("%d / %d (%d%%)\ntx", i, ntx, 100 * i / ntx); } Instant ti = Instant.now(); acme.pay(zzzz, i + 1); Duration elapsed = Duration.between(ti, Instant.now()); long sleep = txperiod - elapsed.toMillis(); if (sleep > 0) { Thread.sleep(sleep); // offer at most 1/txperiod calls/sec. } } return 1; }); } for (int t = 0; t < nthread; t++) { x.add( () -> { for (int i = 0; i < ntx; i++) { if (i % 10 == 0) { System.out.printf("%d / %d (%d%%)\ntx", i, ntx, 100 * i / ntx); } Instant ti = Instant.now(); zzzz.pay(acme, i + 1); Duration elapsed = Duration.between(ti, Instant.now()); long sleep = txperiod - elapsed.toMillis(); if (sleep > 0) { Thread.sleep(sleep); // offer at most 1/txperiod calls/sec. } } return 1; }); } Instant tstart = Instant.now(); List<Future<Integer>> futures = pool.invokeAll(x); for (int t = 0; t < 2 * nthread; t++) { futures.get(t).get(); } Instant tend = Instant.now(); System.out.println("done transacting."); long elapsed = Duration.between(tstart, tend).toMillis(); System.out.printf("elapsed time %dms\n", elapsed); PrintWriter stats = new PrintWriter(new FileWriter("stats.json")); stats.printf("{\"elapsed_ms\": %d, \"txs\": %d}\n", elapsed, ntxTotal); stats.close(); } static Asset getAsset(Context ctx, String id) throws Exception { String q = String.format("alias='%s'", id); Asset.Items assets = new Asset.QueryBuilder().setFilter(q).execute(ctx); if (assets.list.size() != 1) { throw new Exception(String.format("missing asset: %s", id)); } return assets.list.get(0); } static Account getAccount(Context ctx, String id) throws Exception { Account.Items accounts = new Account.QueryBuilder().setFilter(String.format("alias='%s'", id)).execute(ctx); if (accounts.list.size() != 1) { throw new Exception(String.format("missing account: %s", id)); } return accounts.list.get(0); } static void loadKeys(Context ctx) throws Exception { Key.Items keys = MockHsm.Key.list(ctx); while (keys.hasNext()) { Key k = keys.next(); HsmSigner.addKey(k.xpub, k.hsmUrl); } } } class Bank { Asset asset; Account account; Dealer dealer; Context ctx; Bank(Context ctx, Dealer dealer, Asset asset, Account account) { this.ctx = ctx; this.dealer = dealer; this.asset = asset; this.account = account; } void pay(Corp corp, Corp payee, Integer amount) throws Exception { Transaction.Template txTmpl = new Transaction.Builder() .issueById(this.asset.id, BigInteger.valueOf(amount), corp.ref()) .issueById(dealer.usd.id, BigInteger.valueOf(amount), null) .controlWithAccountById( dealer.account.id, this.asset.id, BigInteger.valueOf(amount), null) .controlWithAccountById( payee.bank.account.id, this.dealer.usd.id, BigInteger.valueOf(amount), payee.ref()) .build(ctx); List<Transaction.Template> signedTpls = HsmSigner.sign(Arrays.asList(txTmpl)); List<Transaction.SubmitResponse> txs = Transaction.submit(ctx, signedTpls); for (Transaction.SubmitResponse sr : txs) { System.out.println(String.format("Created tx id=%s", sr.id)); } } void incoming() throws Exception { Transaction.Items transactions = new Transaction.QueryBuilder() .setFilter("outputs(account_id=$1)") .addFilterParameter(this.account.id) .execute(ctx); while (transactions.hasNext()) { Transaction tx = transactions.next(); } } void outgoing() throws Exception { Transaction.Items transactions = new Transaction.QueryBuilder() .setFilter("inputs(action='issuance' AND asset_id = $1)") .addFilterParameter(this.account.id) .execute(ctx); while (transactions.hasNext()) { Transaction tx = transactions.next(); } } } class Corp { String name; Bank bank; Context ctx; Corp(String name, Bank bank, Context ctx) { this.name = name; this.bank = bank; this.ctx = ctx; } void pay(Corp payee, Integer amount) throws Exception { this.bank.pay(this, payee, amount); } HashMap<String, Object> ref() { HashMap<String, Object> m = new HashMap<String, Object>(); m.put("corporate", this.name); return m; } } class Dealer { Account account; Asset usd; Context ctx; Dealer(Context ctx, Account account, Asset usd) { this.account = account; this.usd = usd; this.ctx = ctx; } void reportAllPayments() throws Exception { Transaction.Items transactions = new Transaction.QueryBuilder().setFilter("inputs(action='issue')").execute(this.ctx); System.out.println("report: all dealer payments"); while (transactions.hasNext()) { Transaction tx = transactions.next(); System.out.printf("\ttx: %s\n", tx.id); } } void reportSettlements() throws Exception { Transaction.Items transactions = new Transaction.QueryBuilder().setFilter("outputs(action='retire')").execute(this.ctx); } void reportCurrencyExposure() throws Exception { Balance.Items balanceItems; HashMap<String, BigInteger> exposure = new HashMap<String, BigInteger>(); //Incoming balanceItems = new Balance.QueryBuilder() .setFilter("account_id='" + this.account.id + "' AND asset_tags.currency=$1") .setTimestamp(System.currentTimeMillis()) .execute(this.ctx); while (balanceItems.hasNext()) { Balance balance = balanceItems.next(); String currency = balance.sumBy.get("asset_tags.currency"); BigInteger x = BigInteger.valueOf(0); if (exposure.containsKey(currency)) { x = exposure.get(currency); } exposure.put(currency, x.add(balance.amount)); } //Outgoing balanceItems = new Balance.QueryBuilder() .setFilter("asset_tags.entity='dealer' AND asset_tags.currency=$1") .setTimestamp(System.currentTimeMillis()) .execute(this.ctx); while (balanceItems.hasNext()) { Balance balance = balanceItems.next(); String currency = balance.sumBy.get("asset_tags.currency"); exposure.put(currency, exposure.get(currency).subtract(balance.amount)); } System.out.println("report: dealer currency exposure"); for (String currency : exposure.keySet()) { System.out.printf("\tcurrency: %s amount: %d\n", currency, exposure.get(currency)); } } }
package org.jenetics.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import org.jenetics.util.Accumulators.Mean; import org.jenetics.util.Accumulators.Quantile; import org.jenetics.util.Accumulators.Variance; import org.jscience.mathematics.number.Integer64; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class AccumulatorsTest { private Double[][] _values = null; @BeforeTest public void setup() throws Exception { final InputStream in = getClass().getResourceAsStream("statistic-moments.txt"); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); final List<String> lines = new java.util.ArrayList<String>(1000); String line = null; while ((line = reader.readLine()) != null) { lines.add(line); } _values = new Double[lines.size()][10]; for (int i = 0; i < lines.size(); ++i) { final String[] parts = lines.get(i).split("\\s"); for (int j = 0; j < parts.length; ++j) { _values[i][j] = Double.valueOf(parts[j]); } } } @Test public void quantil() { final Quantile<Integer> quantile = new Quantile<Integer>(0.5); for (int i = 0; i < 1000; ++i) { quantile.accumulate(i); } } @Test public void mean() { final Mean<Double> moment = new Mean<Double>(); for (int i = 0; i < _values.length; ++i) { moment.accumulate(_values[i][0]); Assert.assertEquals(moment.getMean(), _values[i][1]); } } @Test public void variance() { final Variance<Double> moment = new Variance<Double>(); for (int i = 0; i < _values.length; ++i) { moment.accumulate(_values[i][0]); Assert.assertEquals(moment.getMean(), _values[i][1]); Assert.assertEquals(moment.getVariance(), _values[i][6], 0.0000001); } } @Test public void min() { final Integer[] array = new Integer[20]; for (int i = 0; i < array.length; ++i) { array[i] = i; } final Accumulators.Min<Integer> min = new Accumulators.Min<Integer>(); Accumulators.accumulate(Arrays.asList(array), min); Assert.assertEquals(min.getMin(), new Integer(0)); } @Test public void max() { final Integer[] array = new Integer[20]; for (int i = 0; i < array.length; ++i) { array[i] = i; } final Accumulators.Max<Integer> max = new Accumulators.Max<Integer>(); Accumulators.accumulate(Arrays.asList(array), max); Assert.assertEquals(max.getMax(), new Integer(19)); } @Test public void minMax() { final Integer[] array = new Integer[20]; for (int i = 0; i < array.length; ++i) { array[i] = i; } final Accumulators.MinMax<Integer> minMax = new Accumulators.MinMax<Integer>(); Accumulators.accumulate(Arrays.asList(array), minMax); Assert.assertEquals(minMax.getMin(), new Integer(0)); Assert.assertEquals(minMax.getMax(), new Integer(19)); } @Test public void sum() { final Integer64[] array = new Integer64[20]; for (int i = 0; i < array.length; ++i) { array[i] = Integer64.valueOf(i); } final Accumulators.Sum<Integer64> sum = new Accumulators.Sum<Integer64>(); Accumulators.accumulate(Arrays.asList(array), sum); Assert.assertEquals(sum.getSum(), Integer64.valueOf((20*19/2))); } }
package api.web.gw2.mapping.v2.characters; import api.web.gw2.mapping.core.DateValue; import api.web.gw2.mapping.core.EnumValue; import api.web.gw2.mapping.core.IdValue; import api.web.gw2.mapping.core.LevelValue; import api.web.gw2.mapping.core.ListValue; import api.web.gw2.mapping.core.MapValue; import api.web.gw2.mapping.core.OptionalValue; import api.web.gw2.mapping.core.QuantityValue; import api.web.gw2.mapping.core.SetValue; import api.web.gw2.mapping.v2.characters.inventory.InventoryBag; import api.web.gw2.mapping.v2.characters.equipment.Equipment; import java.time.Duration; import java.time.ZonedDateTime; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; public final class JsonpCharacter implements Character { private String name = ""; @EnumValue private CharacterRace race = CharacterRace.UNKNOWN; @EnumValue private CharacterProfession profession = CharacterProfession.UNKNOWN; @EnumValue private CharacterGender gender = CharacterGender.UNKNOWN; @LevelValue private int level = LevelValue.MIN_LEVEL; @OptionalValue @IdValue(flavor = IdValue.Flavor.STRING) private Optional<String> guild = Optional.empty(); @DateValue private ZonedDateTime created = DateValue.DEFAULT; @QuantityValue private Duration age = Duration.ZERO; @QuantityValue private int deaths = 0; @OptionalValue @ListValue private Optional<List<Equipment>> equipment = Optional.empty(); @OptionalValue @ListValue private Optional<List<InventoryBag>> bags = Optional.empty(); @OptionalValue @SetValue private Optional<Set<CharacterCrafting>> crafting = Optional.empty(); @OptionalValue @MapValue private Optional<Map<CharacterGameType, CharacterSpecialization>> specializations = Optional.empty(); /** * Creates a new empty instance. */ public JsonpCharacter() { } @Override public String getName() { return name; } @Override public CharacterRace getRace() { return race; } @Override public CharacterProfession getProfession() { return profession; } @Override public CharacterGender getGender() { return gender; } @Override public int getLevel() { return level; } @Override public Optional<String> getGuild() { return guild; } @Override public ZonedDateTime getCreated() { return created; } @Override public Duration getAge() { return age; } @Override public int getDeaths() { return deaths; } @Override public Optional<List<Equipment>> getEquipment() { return equipment; } @Override public Optional<List<InventoryBag>> getBags() { return bags; } @Override public Optional<Set<CharacterCrafting>> getCrafting() { return crafting; } @Override public Optional<Map<CharacterGameType, CharacterSpecialization>> getSpecialisations() { return specializations; } }
package br.com.juliocnsouza.ocpjp.principios_oo; /** * Planilha.java -> Job: * <p> * @since 26/03/2014 * @version 1.0 * @author Julio Cesar Nunes de Souza (julio.souza@mobilitasistemas.com.br) */ public class Planilha implements Imprimivel { private String[][] dadosPlanilha; public Planilha() { init(); } public void init() { dadosPlanilha = new String[ 5 ][ 5 ]; for ( int a = 0 ; a < 5 ; a++ ) { for ( int b = 0 ; b < 5 ; b++ ) { String coluna = ""; switch ( b ) { case 0: coluna = "A"; break; case 1: coluna = "B"; break; case 2: coluna = "C"; break; case 3: coluna = "D"; break; case 4: coluna = "E"; break; } if ( a == 0 ) { dadosPlanilha[a][b] = "Coluna: " + coluna; } else { dadosPlanilha[a][b] = "Celula: " + coluna + a; } } } } @Override public void imprimir() { System.out.println( "\nImprimindo Planilha" ); for ( int a = 0 ; a < 5 ; a++ ) { for ( int b = 0 ; b < 5 ; b++ ) { if ( b < 4 ) { System.out.print( dadosPlanilha[a][b] + "\t" ); } else { System.out.print( dadosPlanilha[a][b] + "\n" ); } } } } }
package ch.unizh.ini.jaer.projects.minliu; import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.awt.TextRenderer; import com.sun.mail.iap.ByteArray; import eu.seebetter.ini.chips.DavisChip; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.awt.geom.Point2D; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.eventprocessing.filter.Steadicam; import net.sf.jaer.eventprocessing.filter.TransformAtTime; import net.sf.jaer.graphics.ChipRendererDisplayMethodRGBA; import net.sf.jaer.util.filter.HighpassFilter; /** * Uses patch matching to measure local optical flow. <b>Not</b> gradient based, * but rather matches local features backwards in time. * * @author Tobi, Jan 2016 */ @Description("Computes true flow events with speed and vector direction using binary feature patch matching.") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class PatchMatchFlow extends AbstractMotionFlow implements Observer { // These const values are for the fast implementation of the hamming weight calculation private final long m1 = 0x5555555555555555L; //binary: 0101... private final long m2 = 0x3333333333333333L; //binary: 00110011.. private final long m4 = 0x0f0f0f0f0f0f0f0fL; //binary: 4 zeros, 4 ones ... private final long m8 = 0x00ff00ff00ff00ffL; //binary: 8 zeros, 8 ones ... private final long m16 = 0x0000ffff0000ffffL; //binary: 16 zeros, 16 ones ... private final long m32 = 0x00000000ffffffffL; //binary: 32 zeros, 32 ones private final long hff = 0xffffffffffffffffL; //binary: all ones private final long h01 = 0x0101010101010101L; //the sum of 256 to the power of 0,1,2,3... private int[][][] histograms = null; private int numSlices = 3; private int sx, sy; private int currentSliceIdx = 0, tMinus1SliceIdx = 1, tMinus2SliceIdx = 2; private int[][] currentSlice = null, tMinus1Slice = null, tMinus2Slice = null; private BitSet[] histogramsBitSet = null; private BitSet currentSli = null, tMinus1Sli = null, tMinus2Sli = null; private int patchDimension = getInt("patchDimension", 8); private int sliceDurationUs = getInt("sliceDurationUs", 1000); private int sliceEventCount = getInt("sliceEventCount", 1000); private String patchTT = "Patch matching"; private float sadSum = 0; private boolean rewindFlg = false; // The flag to indicate the rewind event. private TransformAtTime lastTransform = null, imageTransform = null; private FilterChain filterChain; private Steadicam cameraMotion; private int packetNum; private int sx2; private int sy2; private double panTranslationDeg; private double tiltTranslationDeg; private float rollDeg; private int lastImuTimestamp = 0; private float panRate = 0, tiltRate = 0, rollRate = 0; // in deg/sec private float panOffset = getFloat("panOffset", 0), tiltOffset = getFloat("tiltOffset", 0), rollOffset = getFloat("rollOffset", 0); private float panDC = 0, tiltDC = 0, rollDC = 0; private boolean showTransformRectangle = getBoolean("showTransformRectangle", true); // calibration private boolean calibrating = false; // used to flag calibration state private int calibrationSampleCount = 0; private int NUM_CALIBRATION_SAMPLES_DEFAULT = 800; // 400 samples /sec protected int numCalibrationSamples = getInt("numCalibrationSamples", NUM_CALIBRATION_SAMPLES_DEFAULT); private CalibrationFilter panCalibrator, tiltCalibrator, rollCalibrator; TextRenderer imuTextRenderer = null; private boolean showGrid = getBoolean("showGrid", true); public enum SliceMethod { ConstantDuration, ConstantEventNumber }; private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.ConstantDuration.toString())); private int eventCounter = 0; // private int sliceLastTs = Integer.MIN_VALUE; private int sliceLastTs = 0; HighpassFilter panTranslationFilter = new HighpassFilter(); HighpassFilter tiltTranslationFilter = new HighpassFilter(); HighpassFilter rollFilter = new HighpassFilter(); private float highpassTauMsTranslation = getFloat("highpassTauMsTranslation", 1000); private float highpassTauMsRotation = getFloat("highpassTauMsRotation", 1000); private boolean highPassFilterEn = getBoolean("highPassFilterEn", false); public PatchMatchFlow(AEChip chip) { super(chip); filterChain = new FilterChain(chip); cameraMotion = new Steadicam(chip); cameraMotion.setFilterEnabled(true); cameraMotion.setDisableRotation(true); cameraMotion.setDisableTranslation(true); // filterChain.add(cameraMotion); setEnclosedFilterChain(filterChain); String imu = "IMU"; chip.addObserver(this); // to allocate memory once chip size is known setPropertyTooltip(patchTT, "patchDimension", "linear dimenion of patches to match, in pixels"); setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels"); setPropertyTooltip(patchTT, "timesliceDurationUs", "duration of patches in us"); setPropertyTooltip(patchTT, "sliceEventNumber", "number of collected events in each bitmap"); setPropertyTooltip(dispTT, "highpassTauMsTranslation", "highpass filter time constant in ms to relax transform back to zero for translation (pan, tilt) components"); setPropertyTooltip(dispTT, "highpassTauMsRotation", "highpass filter time constant in ms to relax transform back to zero for rotation (roll) component"); setPropertyTooltip(dispTT, "highPassFilterEn", "enable the high pass filter or not"); setPropertyTooltip(dispTT, "showTransformRectangle", "Disable to not show the red transform square and red cross hairs"); setPropertyTooltip(imu, "zeroGyro", "zeros the gyro output. Sensor should be stationary for period of 1-2 seconds during zeroing"); setPropertyTooltip(imu, "eraseGyroZero", "Erases the gyro zero values"); panCalibrator = new CalibrationFilter(); tiltCalibrator = new CalibrationFilter(); rollCalibrator = new CalibrationFilter(); rollFilter.setTauMs(highpassTauMsRotation); panTranslationFilter.setTauMs(highpassTauMsTranslation); tiltTranslationFilter.setTauMs(highpassTauMsTranslation); lastTransform = new TransformAtTime(ts, new Point2D.Float( (float)(0), (float)(0)), (float) (0)); } @Override public EventPacket filterPacket(EventPacket in) { setupFilter(in); sadSum = 0; packetNum++; ApsDvsEventPacket in2 = (ApsDvsEventPacket) in; Iterator itr = in2.fullIterator(); // We also need IMU data, so here we use the full iterator. while (itr.hasNext()) { Object ein = itr.next(); if (ein == null) { log.warning("null event passed in, returning input packet"); return in; } extractEventInfo(ein); ApsDvsEvent apsDvsEvent = (ApsDvsEvent) ein; if (apsDvsEvent.isImuSample()) { IMUSample s = apsDvsEvent.getImuSample(); lastTransform = updateTransform(s); } // inItr = in.inputIterator; if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) { imuFlowEstimator.calculateImuFlow((ApsDvsEvent) inItr.next()); setGroundTruth(); } if (xyFilter()) { continue; } countIn++; // compute flow // maybeRotateSlices(); // accumulateEvent(); // SADResult sadResult = minSad(x, y, tMinus2Slice, tMinus1Slice); // sadSum += sadResult.sadValue * sadResult.sadValue; // vx = sadResult.dx * 5; // vy = sadResult.dy * 5; // v = (float) Math.sqrt(vx * vx + vy * vy); long[] testByteArray1 = tMinus1Sli.toLongArray(); long[] testByteArray2 = tMinus2Sli.toLongArray(); long test1 = popcount_3((long) sadSum); int nx = e.x - 120, ny = e.y - 90; e.x = (short) ((((lastTransform.cosAngle * nx) - (lastTransform.sinAngle * ny)) + lastTransform.translationPixels.x) + 120); e.y = (short) (((lastTransform.sinAngle * nx) + (lastTransform.cosAngle * ny) + lastTransform.translationPixels.y) + 90); e.address = chip.getEventExtractor().getAddressFromCell(e.x, e.y, e.getType()); // so event is logged properly to disk if ((e.x > 239) || (e.x < 0) || (e.y > 179) || (e.y < 0)) { e.setFilteredOut(true); // TODO this gradually fills the packet with filteredOut events, which are never seen afterwards because the iterator filters them outputPacket in the reused packet. continue; // discard events outside chip limits for now, because we can't render them presently, although they are valid events } else { e.setFilteredOut(false); } // DavisChip apsDvsChip = (DavisChip) chip; // int frameStartTimestamp = apsDvsChip.getFrameExposureStartTimestampUs(); // int frameEndTimestamp = apsDvsChip.getFrameExposureEndTimestampUs(); // int frameCounter = apsDvsChip.getFrameCount(); // // if a frame has been read outputPacket, then save the last transform to apply to rendering this frame // imageTransform = lastTransform; // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // TODO not ideal (tobi) // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); // reject values that are unreasonable if (accuracyTests()) { continue; } // writeOutputEvent(); if (measureAccuracy) { motionFlowStatistics.update(vx, vy, v, vxGT, vyGT, vGT); } } // if(cameraMotion.getLastTransform() != null) { // lastTransform = cameraMotion.getLastTransform(); // ChipRendererDisplayMethodRGBA displayMethod = (ChipRendererDisplayMethodRGBA) chip.getCanvas().getDisplayMethod(); // After the rewind event, restore sliceLastTs to 0 and rewindFlg to false. // displayMethod.getImageTransform(); // displayMethod.setImageTransform(lastTransform.translationPixels, lastTransform.rotationRad); if(rewindFlg) { rewindFlg = false; sliceLastTs = 0; lastImuTimestamp = 0; panDC = 0; tiltDC = 0; rollDC = 0; } motionFlowStatistics.updatePacket(countIn, countOut); return isShowRawInputEnabled() ? in : dirPacket; } @Override public synchronized void resetFilter() { super.resetFilter(); eventCounter = 0; lastTs = Integer.MIN_VALUE; if (histograms == null || histograms.length != subSizeX || histograms[0].length != subSizeY) { histograms = new int[numSlices][subSizeX][subSizeY]; } for (int[][] a : histograms) { for (int[] b : a) { Arrays.fill(b, 0); } } if (histogramsBitSet == null) { histogramsBitSet = new BitSet[numSlices]; } for(int ii = 0; ii < numSlices; ii ++) { histogramsBitSet[ii] = new BitSet(subSizeX*subSizeY); } currentSliceIdx = 0; tMinus1SliceIdx = 1; tMinus2SliceIdx = 2; assignSliceReferences(); sliceLastTs = 0; packetNum = 0; rewindFlg = true; } private void assignSliceReferences() { currentSlice = histograms[currentSliceIdx]; tMinus1Slice = histograms[tMinus1SliceIdx]; tMinus2Slice = histograms[tMinus2SliceIdx]; currentSli = histogramsBitSet[currentSliceIdx]; tMinus1Sli = histogramsBitSet[tMinus1SliceIdx]; tMinus2Sli = histogramsBitSet[tMinus2SliceIdx]; } @Override public void annotate(GLAutoDrawable drawable) { GL2 gl = null; if (showTransformRectangle) { gl = drawable.getGL().getGL2(); } if (gl == null) { return; } // draw transform gl.glPushMatrix(); // Use this blur rectangle to indicate where is the zero point position. gl.glColor4f(.1f, .1f, 1f, .25f); gl.glRectf(0, 0, 10, 10); gl.glLineWidth(1f); gl.glColor3f(1, 0, 0); if(chip != null) { sx2 = chip.getSizeX() / 2; sy2 = chip.getSizeY() / 2; } else { sx2 = 0; sy2 = 0; } // translate and rotate if(lastTransform != null) { gl.glTranslatef(lastTransform.translationPixels.x + sx2, lastTransform.translationPixels.y + sy2, 0); gl.glRotatef((float) ((lastTransform.rotationRad * 180) / Math.PI), 0, 0, 1); // draw xhairs on frame to help show locations of objects and if they have moved. gl.glBegin(GL.GL_LINES); // sequence of individual segments, in pairs of vertices gl.glVertex2f(0, 0); // start at origin gl.glVertex2f(sx2, 0); // outputPacket to right gl.glVertex2f(0, 0); // origin gl.glVertex2f(-sx2, 0); // outputPacket to left gl.glVertex2f(0, 0); // origin gl.glVertex2f(0, sy2); gl.glVertex2f(0, 0); // origin gl.glVertex2f(0, -sy2); // down gl.glEnd(); // rectangle around transform gl.glTranslatef(-sx2, -sy2, 0); // lower left corner gl.glBegin(GL.GL_LINE_LOOP); // loop of vertices gl.glVertex2f(0, 0); // lower left corner gl.glVertex2f(sx2 * 2, 0); // lower right gl.glVertex2f(2 * sx2, 2 * sy2); // upper right gl.glVertex2f(0, 2 * sy2); // upper left gl.glVertex2f(0, 0); // back of lower left gl.glEnd(); gl.glPopMatrix(); } } @Override public void update(Observable o, Object arg) { super.update(o, arg); if (!isFilterEnabled()) { return; } if (o instanceof AEChip && chip.getNumPixels() > 0) { resetFilter(); } } /** * Computes transform using current gyro outputs based on timestamp supplied * and returns a TransformAtTime object. * * @param timestamp the timestamp in us. * @return the transform object representing the camera rotationRad */ synchronized public TransformAtTime updateTransform(IMUSample imuSample) { int timestamp = imuSample.getTimestampUs(); float dtS = (timestamp - lastImuTimestamp) * 1e-6f; lastImuTimestamp = timestamp; panRate = imuSample.getGyroYawY(); tiltRate = imuSample.getGyroTiltX(); rollRate = imuSample.getGyroRollZ(); if (calibrating) { calibrationSampleCount++; if (calibrationSampleCount > numCalibrationSamples) { calibrating = false; panOffset = panCalibrator.computeAverage(); tiltOffset = tiltCalibrator.computeAverage(); rollOffset = rollCalibrator.computeAverage(); panDC = 0; tiltDC = 0; rollDC = 0; putFloat("panOffset", panOffset); putFloat("tiltOffset", tiltOffset); putFloat("rollOffset", rollOffset); log.info(String.format("calibration finished. %d samples averaged to (pan,tilt,roll)=(%.3f,%.3f,%.3f)", numCalibrationSamples, panOffset, tiltOffset, rollOffset)); } else { panCalibrator.addSample(panRate); tiltCalibrator.addSample(tiltRate); rollCalibrator.addSample(rollRate); } return new TransformAtTime(ts, new Point2D.Float( (float)(0),(float)(0)), (float) (0)); } panDC += getPanRate() * dtS; tiltDC += getTiltRate() * dtS; rollDC += getRollRate() * dtS; if(highPassFilterEn) { panTranslationDeg = panTranslationFilter.filter(panDC, timestamp); tiltTranslationDeg = tiltTranslationFilter.filter(tiltDC, timestamp); rollDeg = rollFilter.filter(rollDC, timestamp); } else { panTranslationDeg = panDC; tiltTranslationDeg = tiltDC; rollDeg = rollDC; } float radValPerPixel = (float) Math.atan(chip.getPixelWidthUm() / (1000 * getLensFocalLengthMm())); // Use the lens focal length and camera resolution. TransformAtTime tr = new TransformAtTime(timestamp, new Point2D.Float( (float) ((Math.PI / 180) * panTranslationDeg/radValPerPixel), (float) ((Math.PI / 180) * tiltTranslationDeg/radValPerPixel)), (-rollDeg * (float) Math.PI) / 180); return tr; } private class CalibrationFilter { int count = 0; float sum = 0; void reset() { count = 0; sum = 0; } void addSample(float sample) { sum += sample; count++; } float computeAverage() { return sum / count; } } /** * @return the panRate */ public float getPanRate() { return panRate - panOffset; } /** * @return the tiltRate */ public float getTiltRate() { return tiltRate - tiltOffset; } /** * @return the rollRate */ public float getRollRate() { return rollRate - rollOffset; } /** * uses the current event to maybe rotate the slices */ private void maybeRotateSlices() { switch (sliceMethod) { case ConstantDuration: int dt = ts - sliceLastTs; if(rewindFlg) { return; } if (dt < sliceDurationUs || dt < 0) { return; } break; case ConstantEventNumber: if (eventCounter++ < sliceEventCount) { return; } } currentSliceIdx = (currentSliceIdx + 1) % numSlices; tMinus1SliceIdx = (tMinus1SliceIdx + 1) % numSlices; tMinus2SliceIdx = (tMinus2SliceIdx + 1) % numSlices; sliceEventCount = 0; sliceLastTs = ts; assignSliceReferences(); } /** * Accumulates the current event to the current slice */ private void accumulateEvent() { currentSlice[x][y] += e.getPolaritySignum(); currentSli.set((x + 1) + y * subSizeX); // All evnets wheather 0 or 1 will be set in the BitSet Slice. } private void clearSlice(int idx) { for (int[] a : histograms[idx]) { Arrays.fill(a, 0); } } synchronized public void doEraseGyroZero() { panOffset = 0; tiltOffset = 0; rollOffset = 0; putFloat("panOffset", 0); putFloat("tiltOffset", 0); putFloat("rollOffset", 0); log.info("calibration erased"); } synchronized public void doZeroGyro() { calibrating = true; calibrationSampleCount = 0; panCalibrator.reset(); tiltCalibrator.reset(); rollCalibrator.reset(); log.info("calibration started"); // panOffset = panRate; // TODO offsets should really be some average over some samples // tiltOffset = tiltRate; // rollOffset = rollRate; } /** * Computes min SAD shift around point x,y using patchDimension and * searchDistance * * @param x coordinate in subsampled space * @param y * @param prevSlice * @param curSlice * @return SADResult that provides the shift and SAD value */ private SADResult minSad(int x, int y, int[][] prevSlice, int[][] curSlice) { // for now just do exhaustive search over all shifts up to +/-searchDistance SADResult sadResult = new SADResult(0, 0, 0); int minSad = Integer.MAX_VALUE, minDx = 0, minDy = 0; for (int dx = -searchDistance; dx < searchDistance; dx++) { for (int dy = -searchDistance; dy < searchDistance; dy++) { int sad = sad(x, y, dx, dy, prevSlice, curSlice); if (sad <= minSad) { minSad = sad; sadResult.dx = dx; sadResult.dy = dy; sadResult.sadValue = minSad; } } } return sadResult; } /** * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx * relative to curSliceIdx patch. * * @param x coordinate in subSampled space * @param y * @param dx * @param dy * @param prevSliceIdx * @param curSliceIdx * @return SAD value */ private int sad(int x, int y, int dx, int dy, int[][] prevSlice, int[][] curSlice) { // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception. if (x < searchDistance - dx || x > subSizeX - searchDistance - dx || x < searchDistance || x > subSizeX - searchDistance || y < searchDistance - dy || y > subSizeY - searchDistance - dy || y < searchDistance || y > subSizeY - searchDistance) { return 0; } int sad = 0; for (int xx = x - searchDistance; xx < x + searchDistance; xx++) { for (int yy = y - searchDistance; yy < y + searchDistance; yy++) { int d = prevSlice[xx + dx][yy + dy] - curSlice[xx][yy]; if (d < 0) { d = -d; } sad += d; } } return sad; } //This uses fewer arithmetic operations than any other known //implementation on machines with fast multiplication. //It uses 12 arithmetic operations, one of which is a multiply. public long popcount_3(long x) { x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... } private class SADResult { float dx, dy; float sadValue; public SADResult(float dx, float dy, float sadValue) { this.dx = dx; this.dy = dy; this.sadValue = sadValue; } @Override public String toString() { return String.format("dx,dy=%d,%5 SAD=%d",dx,dy,sadValue); } } /** * @return the patchDimension */ public int getPatchDimension() { return patchDimension; } /** * @param patchDimension the patchDimension to set */ public void setPatchDimension(int patchDimension) { this.patchDimension = patchDimension; putInt("patchDimension", patchDimension); } /** * @return the sliceMethod */ public SliceMethod getSliceMethod() { return sliceMethod; } /** * @param sliceMethod the sliceMethod to set */ public void setSliceMethod(SliceMethod sliceMethod) { this.sliceMethod = sliceMethod; putString("sliceMethod", sliceMethod.toString()); } /** * @return the sliceDurationUs */ public int getSliceDurationUs() { return sliceDurationUs; } /** * @param sliceDurationUs the sliceDurationUs to set */ public void setSliceDurationUs(int sliceDurationUs) { this.sliceDurationUs = sliceDurationUs; putInt("sliceDurationUs", sliceDurationUs); } public boolean isShowTransformRectangle() { return showTransformRectangle; } public void setShowTransformRectangle(boolean showTransformRectangle) { this.showTransformRectangle = showTransformRectangle; } /** * @return the sliceEventCount */ public int getSliceEventCount() { return sliceEventCount; } /** * @param sliceEventCount the sliceEventCount to set */ public void setSliceEventCount(int sliceEventCount) { this.sliceEventCount = sliceEventCount; putInt("sliceEventCount", sliceEventCount); } public float getHighpassTauMsTranslation() { return highpassTauMsTranslation; } public void setHighpassTauMsTranslation(float highpassTauMs) { this.highpassTauMsTranslation = highpassTauMs; putFloat("highpassTauMsTranslation", highpassTauMs); panTranslationFilter.setTauMs(highpassTauMs); tiltTranslationFilter.setTauMs(highpassTauMs); } public float getHighpassTauMsRotation() { return highpassTauMsRotation; } public void setHighpassTauMsRotation(float highpassTauMs) { this.highpassTauMsRotation = highpassTauMs; putFloat("highpassTauMsRotation", highpassTauMs); rollFilter.setTauMs(highpassTauMs); } public boolean isHighPassFilterEn() { return highPassFilterEn; } public void setHighPassFilterEn(boolean highPassFilterEn) { this.highPassFilterEn = highPassFilterEn; putBoolean("highPassFilterEn", highPassFilterEn); } }
package com.coderevisited.coding; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class ReplaceWithNextGreatest { public static void main(String[] args) { PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int[] array = new int[]{16, 6, 9, 10, 11, 17, 4, 3, 9, 8, 5, 2, 14}; replaceWithNextGreatest(array); printArray(array, pw); array = new int[]{-2, -7, -8}; replaceWithNextGreatest(array); printArray(array, pw); pw.close(); } private static void replaceWithNextGreatest(int[] array) { int max = Integer.MIN_VALUE; for (int i = array.length - 1; i >= 0; i int current = array[i]; array[i] = max; max = max > current ? max : current; } array[array.length - 1] = -1; } private static void printArray(int[] array, PrintWriter pw) { for (int i : array) { pw.print(i + " "); } pw.println(); } }
package scalac.transformer.matching; import ch.epfl.lamp.util.Position; import scalac.*; import scalac.ast.*; import scalac.util.*; import scalac.symtab.*; import PatternNode.*; import Tree.*; public class PatternMatcher extends PatternTool { protected boolean optimize = true; protected boolean delegateSequenceMatching = false; protected boolean doBinding = true; /** the owner of the pattern matching expression */ protected Symbol owner; /** the selector expression */ protected Tree selector; /** the root of the pattern node structure */ protected PatternNode root; /** the symbol of the result variable */ protected Symbol resultVar; /** methods to generate scala code */ protected CodeFactory cf; /** methods to create pattern nodes */ protected PatternNodeCreator mk; /** constructor */ public PatternMatcher(Unit unit, Tree selector, Symbol owner, Type resultType) { super(unit); initialize(selector, owner, resultType, true); } /** constructor, used in subclass ALgebraicMatcher */ protected PatternMatcher(Unit unit) { super(unit); } /** init method, also needed in subclass AlgebraicMatcher */ protected void initialize(Tree selector, Symbol owner, Type resultType, boolean doBinding) { this.mk = new PatternNodeCreator(unit, owner); this.cf = new CodeFactory(unit, selector.pos); this.root = mk.ConstrPat(selector.pos, selector.type.widen()); this.root.and = mk.Header(selector.pos, selector.type.widen(), gen.Ident(selector.pos, root.symbol())); this.resultVar = new TermSymbol(selector.pos, fresh.newName(RESULT_N), owner, Modifiers.MUTABLE); this.resultVar.setType(resultType); this.owner = owner; this.selector = selector; this.optimize &= (unit.global.target == Global.TARGET_JVM); this.doBinding = doBinding; } /** pretty printer */ public void print() { print(root.and, ""); } public void print(PatternNode patNode, String indent) { if (patNode == null) System.out.println(indent + "NULL"); else switch (patNode) { case Header(Tree selector, Header next): System.out.println(indent + "HEADER(" + patNode.type + ", " + selector + ")"); print(patNode.or, indent + "|"); if (next != null) print(next, indent); break; case ConstrPat(Symbol casted): String s = "-- " + patNode.type.symbol().name + "(" + patNode.type + ", " + casted + ") -> "; String ind = indent; indent = (patNode.or != null) ? indent : indent.substring(0, indent.length() - 1) + " "; for (int i = 0; i < s.length(); i++) indent += " "; System.out.println(ind + s); print(patNode.and, indent); if (patNode.or != null) print(patNode.or, ind); break; case SequencePat( Symbol casted, int plen ): String s = "-- " + patNode.type.symbol().name + "(" + patNode.type + ", " + casted + ", " + plen + ") -> "; String ind = indent; indent = (patNode.or != null) ? indent : indent.substring(0, indent.length() - 1) + " "; for (int i = 0; i < s.length(); i++) indent += " "; System.out.println(ind + s); print(patNode.and, indent); if (patNode.or != null) print(patNode.or, ind); break; case DefaultPat(): System.out.println(indent + " print(patNode.and, indent.substring(0, indent.length() - 1) + " "); if (patNode.or != null) print(patNode.or, indent); break; case ConstantPat(Object value): String s = "-- CONST(" + value + ") -> "; String ind = indent; indent = (patNode.or != null) ? indent : indent.substring(0, indent.length() - 1) + " "; for (int i = 0; i < s.length(); i++) indent += " "; System.out.println(ind + s); print(patNode.and, indent); if (patNode.or != null) print(patNode.or, ind); break; case VariablePat(Tree tree): String s = "-- STABLEID(" + tree + ": " + patNode.type + ") -> "; String ind = indent; indent = (patNode.or != null) ? indent : indent.substring(0, indent.length() - 1) + " "; for (int i = 0; i < s.length(); i++) indent += " "; System.out.println(ind + s); print(patNode.and, indent); if (patNode.or != null) print(patNode.or, ind); break; case AltPat(Header header): System.out.println(indent + "-- ALTERNATIVES:"); print(header, indent + " * "); print(patNode.and, indent + " * -> "); if (patNode.or != null) print(patNode.or, indent); break; case Body(_, Tree[] guards, Tree[] stats): if ((guards.length == 0) && (stats.length == 0)) System.out.println(indent + "true"); else System.out.println(indent + "BODY(" + stats.length + ")"); break; } } /** enters a sequence of cases into the pattern matcher */ public void enter(Tree[] cases) { for( int i = 0; i < cases.length; i++ ) enter(cases[i]); } /** enter a single case into the pattern matcher */ public void enter(Tree caseDef) { switch (caseDef) { case CaseDef(Tree pat, Tree guard, Tree body): CaseEnv env = new CaseEnv(owner, unit); // PatternNode matched = match(pat, root); PatternNode target = enter1(pat, -1, root, root.symbol(), env); // if (target.and != null) // unit.error(pat.pos, "duplicate case"); if (target.and == null) target.and = mk.Body(caseDef.pos, env.boundVars(), guard, body); else if (target.and instanceof Body) updateBody((Body)target.and, env.boundVars(), guard, body); else unit.error(pat.pos, "duplicate case"); } } protected void updateBody(Body tree, ValDef[] bound, Tree guard, Tree body) { if (tree.guard[tree.guard.length - 1] == Tree.Empty) { //unit.error(body.pos, "unreachable code"); } else { ValDef[][] bd = new ValDef[tree.bound.length + 1][]; Tree[] ng = new Tree[tree.guard.length + 1]; Tree[] nb = new Tree[tree.body.length + 1]; System.arraycopy(tree.bound, 0, bd, 0, tree.bound.length); System.arraycopy(tree.guard, 0, ng, 0, tree.guard.length); System.arraycopy(tree.body, 0, nb, 0, tree.body.length); bd[bd.length - 1] = bound; ng[ng.length - 1] = guard; nb[nb.length - 1] = body; tree.bound = bd; tree.guard = ng; tree.body = nb; } } /* // unused, thus commented out ! public PatternNode match(Tree pat, PatternNode target) { // advance one step in pattern PatternNode next = target.and; // we are done (no match yet) if (next == null) return null; // check if matched switch (next) { case Body(_, _, _): return next; case Header(_, _): Header header = (Header)next; // get pattern arguments Tree[] patArgs = patternArgs(pat); // get next pattern node PatternNode patNode = patternNode(pat, header, null); do { next = header; while ((next = next.or) != null) if (superPat(next, patNode) && ((target = match(patArgs, next)) != null)) return target; else if (isDefaultPat(next)) return next.and; } while ((header = header.next) != null); return null; default: throw new ApplicationError(); } } public PatternNode match(Tree[] pats, PatternNode target) { for (int i = 0; i < pats.length; i++) if ((target = match(pats[i], target)) == null) return null; return target; } */ protected Tree[] patternArgs(Tree tree) { switch (tree) { case Bind(_, Tree pat): return patternArgs(pat); case Apply(_, Tree[] args): if ( isSeqApply((Apply) tree) && !delegateSequenceMatching) switch (args[0]) { case Sequence(Tree[] ts): return ts; } return args; case Sequence(Tree[] ts): if (!delegateSequenceMatching) return ts; return Tree.EMPTY_ARRAY; default: return Tree.EMPTY_ARRAY; } } protected boolean isSeqApply( Tree.Apply tree ) { return (tree.args.length == 1 && (tree.type.symbol().flags & Modifiers.CASE) == 0); } protected PatternNode patternNode(Tree tree, Header header, CaseEnv env) { switch (tree) { case Bind(Name name, Typed( Ident( Names.PATTERN_WILDCARD ), Tree tpe)): // little opt. for x@_:Type if(header.type.isSubType(tpe.type)) { PatternNode node = mk.DefaultPat(tree.pos, tpe.type); env.newBoundVar( tree.symbol(), tree.type, header.selector ); return node; } else { ConstrPat node = mk.ConstrPat(tree.pos, tpe.type); env.newBoundVar( tree.symbol(), tree.type, gen.Ident(tree.pos, node.casted)); return node; } case Bind(Name name, Ident( Names.PATTERN_WILDCARD )): // little opt. for x@_ PatternNode node = mk.DefaultPat(tree.pos, header.type); if ((env != null) && (tree.symbol() != defs.PATTERN_WILDCARD)) env.newBoundVar( tree.symbol(), tree.type, header.selector); return node; case Bind(Name name, Tree pat): PatternNode node = patternNode(pat, header, env); if ((env != null) && (tree.symbol() != defs.PATTERN_WILDCARD)) { Symbol casted = node.symbol(); Tree theValue = (casted == Symbol.NONE) ? header.selector : gen.Ident(tree.pos, casted); env.newBoundVar( tree.symbol(), tree.type, theValue ); } return node; case Apply(Tree fn, Tree[] args): // pattern with args if(isSeqApply((Apply)tree)) { if (!delegateSequenceMatching) { switch (args[0]) { case Sequence(Tree[] ts): return mk.SequencePat( tree.pos, tree.type, ts.length ); } } else { PatternNode res = mk.ConstrPat(tree.pos, tree.type); res.and = mk.Header(tree.pos, header.type, header.selector); res.and.and = mk.SeqContainerPat( tree.pos, tree.type, args[ 0 ] ); return res; } } else if ((fn.symbol() != null) && fn.symbol().isStable()) return mk.VariablePat(tree.pos, tree); return mk.ConstrPat(tree.pos, tree.type); case Typed(Ident ident, Tree tpe): // variable pattern boolean doTest = header.type.isSubType(tpe.type); PatternNode node = doTest ? mk.DefaultPat(tree.pos, tpe.type) : mk.ConstrPat(tree.pos, tpe.type); if ((env != null) && (ident.symbol() != defs.PATTERN_WILDCARD)) switch (node) { case ConstrPat(Symbol casted): env.newBoundVar( ((Tree.Typed)tree).expr.symbol(), tpe.type, gen.Ident(tree.pos, casted)); break; default: env.newBoundVar( ((Tree.Typed)tree).expr.symbol(), tpe.type, doTest ? header.selector : gen.Ident(tree.pos, ((ConstrPat) node).casted)); } return node; case Ident(Name name): // pattern without args or variable if (tree.symbol() == defs.PATTERN_WILDCARD) return mk.DefaultPat(tree.pos, header.type); else if (tree.symbol().isPrimaryConstructor()) { assert false; return mk.ConstrPat(tree.pos, tree.type); } else if (name.isVariable()) { assert false; if (env != null) env.newBoundVar(tree.symbol(), tree.type, header.selector); return mk.DefaultPat(tree.pos, header.type); } else return mk.VariablePat(tree.pos, tree); case Select(_, Name name): // variable if (tree.symbol().isPrimaryConstructor()) return mk.ConstrPat(tree.pos, tree.type); else return mk.VariablePat(tree.pos, tree); case Literal(Object value): return mk.ConstantPat(tree.pos, tree.type, value); case Sequence(Tree[] ts): if ( !delegateSequenceMatching ) { return mk.SequencePat(tree.pos, tree.type, ts.length); } else { return mk.SeqContainerPat(tree.pos, tree.type, tree); } case Alternative(Tree[] ts): assert ts.length > 1; PatternNode subroot = mk.ConstrPat(header.pos, header.type); subroot.and = mk.Header(header.pos, header.type, header.selector.duplicate()); CaseEnv subenv = new CaseEnv(owner, unit); for (int i = 0; i < ts.length; i++) { PatternNode target = enter1(ts[i], -1, subroot, subroot.symbol(), subenv); target.and = mk.Body(tree.pos); } return mk.AltPat(tree.pos, (Header)subroot.and); default: new scalac.ast.printer.TextTreePrinter().print(tree).flush(); throw new ApplicationError("unit = " + unit + "; tree = "+tree); } } protected boolean superPat(PatternNode p, PatternNode q) { switch (p) { case DefaultPat(): switch (q) { case DefaultPat(): return true; } return false; case ConstrPat(_): switch (q) { case ConstrPat(_): return q.type.isSubType(p.type); } return false; case SequencePat(_, int plen): switch (q) { case SequencePat(_, int qlen): return (plen == qlen) && q.type.isSubType(p.type); } return false; case ConstantPat(Object pval): switch (q) { case ConstantPat(Object qval): return pval.equals(qval); } return false; case VariablePat(Tree tree): switch (q) { case VariablePat(Tree other): return (tree.symbol() != null) && (tree.symbol().kind != Kinds.NONE) && (tree.symbol().kind != Kinds.ERROR) && (tree.symbol() == other.symbol()); } return false; } return false; } protected boolean samePat(PatternNode p, PatternNode q) { switch (p) { case ConstrPat(_): switch (q) { case ConstrPat(_): return q.type.isSameAs(p.type); } return false; case SequencePat(_, int plen): switch (q) { case SequencePat(_, int qlen): return (plen == qlen) && q.type.isSameAs(p.type); } return false; default: return superPat(p, q); } } protected boolean isDefaultPat(PatternNode p) { switch (p) { case DefaultPat(): return true; default: return false; } } public PatternNode enter(Tree pat, int index, PatternNode target, Symbol casted, CaseEnv env) { switch (target) { case ConstrPat(Symbol newCasted): return enter1(pat, index, target, newCasted, env); case SequencePat(Symbol newCasted, int len): return enter1(pat, index, target, newCasted, env); default: return enter1(pat, index, target, casted, env); } } public PatternNode enter1(Tree pat, int index, PatternNode target, Symbol casted, CaseEnv env) { //System.err.println("enter(" + pat + ", " + index + ", " + target + ", " + casted + ")"); // get pattern arguments Tree[] patArgs = patternArgs(pat); //System.err.println("patArgs.length = " +patArgs.length); // advance one step in pattern Header curHeader = (Header)target.and; // check if we have to add a new header if (curHeader == null) { assert index >= 0 : casted; if (casted.pos == Position.FIRSTPOS) { //Symbol atSym = casted.type().lookup(APPLY_N); Tree t = gen.mkApply_V( gen.Select( gen.Ident(pat.pos, casted), defs.FUNCTION_APPLY(1)), new Tree[]{gen.mkIntLit(pat.pos, index)}); Type seqType = t.type; /* atSym); Type seqType = casted.type().baseType(defs.SEQ_CLASS).typeArgs()[0]; Tree t = gen.Select(gen.Ident(pat.pos, casted), atSym); switch (t.type()) { case OverloadedType(Symbol[] alts, Type[] alttypes): infer.methodAlternative(t, alts, alttypes, new Type[]{defs.INT_TYPE()}, seqType); } t = gen.mkApply_V(t, new Tree[]{gen.mkIntLit(pat.pos, index)}); */ target.and = curHeader = mk.Header(pat.pos, seqType, t); } else { Symbol ts = ((ClassSymbol) casted.getType().symbol()) .caseFieldAccessor(index); Type accType = casted.getType().memberType(ts); Tree accTree = gen.Select(gen.Ident(pat.pos, casted), ts); switch (accType) { // scala case accessor case MethodType(_, _): target.and = curHeader = mk.Header( pat.pos, accType.resultType(), gen.mkApply__(accTree)); break; // jaco case accessor default: target.and = curHeader = mk.Header(pat.pos, accType, accTree); } } curHeader.or = patternNode(pat, curHeader, env); return enter(patArgs, curHeader.or, casted, env); } // find most recent header while (curHeader.next != null) curHeader = curHeader.next; // create node PatternNode patNode = patternNode(pat, curHeader, env); PatternNode next = curHeader; // enter node while (true) if (samePat(next, patNode)) return enter(patArgs, next, casted, env); else if (isDefaultPat(next) || ((next.or == null) && (isDefaultPat(patNode) || superPat(next, patNode)))) return enter( patArgs, (curHeader = (curHeader.next = mk.Header(patNode.pos, curHeader.type, curHeader.selector))).or = patNode, casted, env); else if (next.or == null) return enter(patArgs, next.or = patNode, casted, env); else next = next.or; } /** calls enter for an array of patterns, see enter */ public PatternNode enter(Tree[] pats, PatternNode target, Symbol casted, CaseEnv env) { switch (target) { case ConstrPat(Symbol newCasted): casted = newCasted; break; case SequencePat(Symbol newCasted, int len): casted = newCasted; break; } for (int i = 0; i < pats.length; i++) target = enter1(pats[i], i, target, casted, env); return target; } protected int nCaseComponents(Tree tree) { switch (tree) { case Apply(Tree fn, _): Type tpe = tree.type.symbol().primaryConstructor().type(); //System.out.println("~~~ " + tree.type() + ", " + tree.type().symbol().primaryConstructor()); switch (tpe) { // I'm not sure if this is a good idea, but obviously, currently all case classes // without constructor arguments have type NoType case NoType: return 0; case MethodType(Symbol[] args, _): return args.length; case PolyType(Symbol[] tvars, MethodType(Symbol[] args, _)): return args.length; case PolyType(Symbol[] tvars, _): return 0; default: throw new ApplicationError("not yet implemented;" + "pattern matching for " + tree + ": " + tpe); } } return 0; } //////////// generator methods public Tree toTree() { if (optimize && isSimpleIntSwitch()) return intSwitchToTree(); else if (false && optimize && isSimpleSwitch()) return switchToTree(); else return generalSwitchToTree(); } protected boolean isSimpleIntSwitch() { if (selector.type.widen().isSameAs(defs.INT_TYPE())) { PatternNode patNode = root.and; while (patNode != null) { PatternNode node = patNode; while ((node = node.or) != null) { switch (node) { case ConstantPat(_): break; default: return false; } switch (node.and) { case Body(ValDef[][] bound, Tree[] guard, _): if ((guard.length > 1) || (guard[0] != Tree.Empty) || (bound[0].length > 0)) return false; break; default: return false; } } patNode = patNode.next(); } return true; } else return false; } protected boolean isSimpleSwitch() { print(); PatternNode patNode = root.and; while (patNode != null) { PatternNode node = patNode; while ((node = node.or) != null) { boolean isCase = false; switch (node) { case VariablePat(Tree tree): System.out.println(((tree.symbol().flags & Modifiers.CASE) != 0)); break; case ConstrPat(_): System.out.println(node.type + " / " + ((node.type.symbol().flags & Modifiers.CASE) != 0)); PatternNode inner = node.and; outer: while (true) { switch (inner) { case Header(_, Header next): if (next != null) return false; inner = inner.or; break; case DefaultPat(): inner = inner.and; break; case Body(ValDef[][] bound, Tree[] guard, _): if ((guard.length > 1) || (guard[0] != Tree.Empty)) return false; break outer; default: System.out.println(inner); return false; } } break; default: return false; } } patNode = patNode.next(); } return true; } static class TagBodyPair { int tag; Tree body; TagBodyPair next; TagBodyPair(int tag, Tree body, TagBodyPair next) { this.tag = tag; this.body = body; this.next = next; } int length() { return (next == null) ? 1 : (next.length() + 1); } } static TagBodyPair insert(int tag, Tree body, TagBodyPair current) { if (current == null) return new TagBodyPair(tag, body, null); else if (tag > current.tag) return new TagBodyPair(current.tag, current.body, insert(tag, body, current.next)); else return new TagBodyPair(tag, body, current); } protected int numCases(PatternNode patNode) { int n = 0; while ((patNode = patNode.or) != null) switch (patNode) { case DefaultPat(): break; default: n++; } return n; } protected Tree defaultBody(PatternNode patNode, Tree otherwise) { while (patNode != null) { PatternNode node = patNode; while ((node = node.or) != null) switch (node) { case DefaultPat(): return bodyToTree(node.and); } patNode = patNode.next(); } return otherwise; } /** This method translates pattern matching expressions that match * on integers on the top level. */ public Tree intSwitchToTree() { //print(); int ncases = numCases(root.and); Tree matchError = cf.ThrowMatchError(selector.pos, resultVar.getType()); // without a case, we return a match error if there is no default case if (ncases == 0) return defaultBody(root.and, matchError); // for one case we use a normal if-then-else instruction else if (ncases == 1) { switch (root.and.or) { case ConstantPat(Object value): return gen.If( cf.Equals(selector, gen.mkLit(root.and.or.pos, value)), bodyToTree(root.and.or.and), defaultBody(root.and, matchError)); default: return generalSwitchToTree(); } } // if we have more than 2 cases than use a switch statement switch (root.and) { case Header(_, Header next): TagBodyPair mappings = null; Tree defaultBody = null; PatternNode patNode = root.and; while (patNode != null) { PatternNode node = patNode.or; while (node != null) { switch (node) { case DefaultPat(): if (defaultBody != null) throw new ApplicationError(); defaultBody = bodyToTree(node.and); node = node.or; break; case ConstantPat(Object value): mappings = insert( ((Integer)value).intValue(), bodyToTree(node.and), mappings); node = node.or; break; default: throw new ApplicationError(node.toString()); } } patNode = patNode.next(); } if (defaultBody == null) defaultBody = cf.ThrowMatchError(selector.pos, resultVar.getType()); if (mappings == null) { return gen.Switch(selector, new int[0], new Tree[0], defaultBody, resultVar.getType()); } else { int n = mappings.length(); int[] tags = new int[n]; Tree[] bodies = new Tree[n]; n = 0; while (mappings != null) { tags[n] = mappings.tag; bodies[n++] = mappings.body; mappings = mappings.next; } return gen.Switch(selector, tags, bodies, defaultBody, resultVar.getType()); } default: throw new ApplicationError(); } } protected Tree bodyToTree(PatternNode node) { switch (node) { case Body(_, _, Tree[] body): return body[0]; default: throw new ApplicationError(); } } public Tree switchToTree() { throw new Error(); } public Tree generalSwitchToTree() { TreeList ts = new TreeList(); ts.append(gen.ValDef(root.symbol(), selector)); ts.append(gen.ValDef(resultVar, gen.mkDefaultValue(selector.pos, resultVar.getType()))); ts.append( gen.If( selector.pos, toTree(root.and), gen.Ident(selector.pos, resultVar), cf.ThrowMatchError(selector.pos, resultVar.getType()))); return gen.mkBlock(selector.pos, ts.toArray()); } protected Tree toTree(PatternNode node) { Tree res = gen.mkBooleanLit(node.pos, false); while (node != null) switch (node) { case Header(Tree selector, Header next): //res = cf.And(mkNegate(res), toTree(node.or, selector)); //System.out.println("HEADER TYPE = " + selector.type); if (optimize(node.type, node.or)) res = cf.Or(res, toOptTree(node.or, selector)); else res = cf.Or(res, toTree(node.or, selector)); node = next; break; case Body(ValDef[][] bound, Tree[] guard, Tree[] body): if ((bound.length == 0) && (guard.length == 0) && (body.length == 0)) { return gen.mkBooleanLit(node.pos, true); // cf.Or(res, gen.mkBooleanLit(node.pos, true)); } else if (!doBinding) bound = new ValDef[][]{new ValDef[]{}}; for (int i = guard.length - 1; i >= 0; i Tree[] ts = new Tree[bound[i].length + 1]; System.arraycopy(bound[i], 0, ts, 0, bound[i].length); ts[bound[i].length] = gen.mkBlock( new Tree[]{ gen.Assign( gen.Ident(body[i].pos, resultVar), body[i]), gen.mkBooleanLit(body[i].pos, true) }); if (guard[i] != Tree.Empty) ts[bound[i].length] = cf.And(guard[i], ts[bound[i].length]); res = cf.Or(gen.mkBlock(body[i].pos, ts), res); } return res; default: throw new ApplicationError(); } return res; } protected boolean optimize(Type selType, PatternNode alternatives) { if (!optimize || !selType.isSubType(defs.OBJECT_TYPE())) return false; int cases = 0; while (alternatives != null) { switch (alternatives) { case ConstrPat(_): if (alternatives.type.symbol().isCaseClass()) cases++; else return false; break; case DefaultPat(): break; default: return false; } alternatives = alternatives.or; } return cases > 2; } static class TagNodePair { int tag; PatternNode node; TagNodePair next; TagNodePair(int tag, PatternNode node, TagNodePair next) { this.tag = tag; this.node = node; this.next = next; } int length() { return (next == null) ? 1 : (next.length() + 1); } } static TagNodePair insert(int tag, PatternNode node, TagNodePair current) { if (current == null) return new TagNodePair(tag, node, null); else if (tag > current.tag) return new TagNodePair(current.tag, current.node, insert(tag, node, current.next)); else if (tag == current.tag) { PatternNode old = current.node; (current.node = node).or = old; return current; } else return new TagNodePair(tag, node, current); } static TagNodePair insertNode(int tag, PatternNode node, TagNodePair current) { PatternNode newnode = node.dup(); newnode.or = null; return insert(tag, newnode, current); } protected Tree toOptTree(PatternNode node, Tree selector) { //System.err.println("pm.toOptTree called"+node); TagNodePair cases = null; PatternNode defaultCase = null; while (node != null) switch (node) { case ConstrPat(Symbol casted): cases = insertNode(node.type.symbol().tag(), node, cases); node = node.or; break; case DefaultPat(): defaultCase = node; node = node.or; break; default: throw new ApplicationError(); } int n = cases.length(); int[] tags = new int[n]; Tree[] bodies = new Tree[n]; n = 0; while (cases != null) { tags[n] = cases.tag; bodies[n++] = toTree(cases.node, selector); cases = cases.next; } return gen.Switch( gen.mkApply__(gen.Select(selector.duplicate(), defs.OBJECT_TAG())), tags, bodies, (defaultCase == null) ? gen.mkBooleanLit(selector.pos, false) : toTree(defaultCase.and), defs.BOOLEAN_TYPE()); } protected Tree toTree(PatternNode node, Tree selector) { //System.err.println("pm.toTree called"+node); if (node == null) return gen.mkBooleanLit(selector.pos, false); switch (node) { case DefaultPat(): return toTree(node.and); case ConstrPat(Symbol casted): return gen.If( gen.mkIsInstanceOf(selector.duplicate(), node.type), gen.mkBlock( new Tree[]{ gen.ValDef(casted, gen.mkAsInstanceOf(selector.duplicate(), node.type)), toTree(node.and)}), toTree(node.or, selector.duplicate())); case SequencePat(Symbol casted, int len): return gen.If( cf.And( gen.mkIsInstanceOf(selector.duplicate(), node.type), cf.Equals( gen.mkApply__( gen.Select( gen.mkAsInstanceOf( selector.duplicate(), node.type), defs.SEQ_LENGTH())), gen.mkIntLit(selector.pos, len))), gen.mkBlock( new Tree[]{ gen.ValDef(casted, gen.mkAsInstanceOf(selector.duplicate(), node.type)), toTree(node.and)}), toTree(node.or, selector.duplicate())); case ConstantPat(Object value): return gen.If( cf.Equals(selector.duplicate(), gen.mkLit(selector.pos, value)), toTree(node.and), toTree(node.or, selector.duplicate())); case VariablePat(Tree tree): return gen.If( cf.Equals(selector.duplicate(), tree), toTree(node.and), toTree(node.or, selector.duplicate())); case AltPat(Header header): return gen.If( toTree(header), toTree(node.and), toTree(node.or, selector.duplicate())); default: throw new ApplicationError(); } } }
package com.dmdirc.ui.swing.components; import com.dmdirc.commandparser.parsers.CommandParser; import com.dmdirc.ui.input.InputHandler; import com.dmdirc.ui.interfaces.InputField; import com.dmdirc.ui.interfaces.InputWindow; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.KeyStroke; import javax.swing.text.JTextComponent; /** * Swing input handler. */ public class SwingInputHandler extends InputHandler implements KeyListener { /** * Creates a new instance of InputHandler. Adds listeners to the target * that we need to operate. * * @param target The text field this input handler is dealing with. * @param commandParser The command parser to use for this text field. * @param parentWindow The window that owns this input handler */ public SwingInputHandler(final InputField target, final CommandParser commandParser, final InputWindow parentWindow) { super(target, commandParser, parentWindow); } /** {@inheritDoc} */ @Override protected void addUpHandler() { ((JTextComponent) target).getActionMap().put("upArrow", new AbstractAction() { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { doBufferUp(); } }); ((JTextComponent) target).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "upArrow"); } /** {@inheritDoc} */ @Override protected void addDownHandler() { ((JTextComponent) target).getActionMap().put("downArrow", new AbstractAction() { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { doBufferDown(); } }); ((JTextComponent) target).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "downArrow"); } /** {@inheritDoc} */ @Override protected void addTabHandler() { ((JTextComponent) target).getActionMap().put("tabPressed", new AbstractAction() { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { doTabCompletion(); } }); ((JTextComponent) target).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tabPressed"); } /** {@inheritDoc} */ @Override protected void addEnterHandler() { ((JTextComponent) target).getActionMap().put("enterButton", new AbstractAction() { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** {@inheritDoc} */ @Override public void actionPerformed(ActionEvent e) { enterPressed(target.getText()); } }); ((JTextComponent) target).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW). put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enterButton"); } /** {@inheritDoc} */ @Override protected void addKeyHandler() { target.addKeyListener(this); } /** * {@inheritDoc} * * @param e Key event */ @Override public void keyTyped(final KeyEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Key event */ @Override public void keyPressed(final KeyEvent e) { if (e.getKeyCode() != KeyEvent.VK_TAB && e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) { handleKeyPressed(e.getKeyCode(), e.isShiftDown(), e.isControlDown()); } } /** * {@inheritDoc} * * @param e Key event */ @Override public void keyReleased(final KeyEvent e) { //Ignore } }
package com.github.nutomic.controldlna.gui; import java.util.List; import org.teleal.cling.support.model.item.Item; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v7.app.MediaRouteDiscoveryFragment; import android.support.v7.media.MediaControlIntent; import android.support.v7.media.MediaItemStatus; import android.support.v7.media.MediaRouteSelector; import android.support.v7.media.MediaRouter; import android.support.v7.media.MediaRouter.Callback; import android.support.v7.media.MediaRouter.ProviderInfo; import android.support.v7.media.MediaRouter.RouteInfo; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.github.nutomic.controldlna.R; import com.github.nutomic.controldlna.gui.MainActivity.OnBackPressedListener; import com.github.nutomic.controldlna.mediarouter.MediaRouterPlayService; import com.github.nutomic.controldlna.mediarouter.MediaRouterPlayServiceBinder; import com.github.nutomic.controldlna.utility.FileArrayAdapter; import com.github.nutomic.controldlna.utility.RouteAdapter; /** * Controls media playback by showing a list of routes, and after selecting one, * the current playlist and playback controls. * * @author Felix Ableitner * */ public class RouteFragment extends MediaRouteDiscoveryFragment implements OnBackPressedListener, OnItemClickListener, OnClickListener, OnSeekBarChangeListener, OnScrollListener { private ListView mListView; private View mControls; private SeekBar mProgressBar; private ImageButton mPlayPause; private ImageButton mShuffle; private ImageButton mRepeat; private TextView mCurrentTimeView; private TextView mTotalTimeView; private View mCurrentTrackView; private boolean mPlaying; private RouteAdapter mRouteAdapter; private FileArrayAdapter mPlaylistAdapter; private RouteInfo mSelectedRoute; /** * Count of the number of taps on the previous button within the * doubletap interval. */ private int mPreviousTapCount = 0; /** * If true, the item at this position will be played as soon as a route is selected. */ private int mStartPlayingOnSelect = -1; private MediaRouterPlayService mMediaRouterPlayService; private ServiceConnection mPlayServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { MediaRouterPlayServiceBinder binder = (MediaRouterPlayServiceBinder) service; mMediaRouterPlayService = binder.getService(); mMediaRouterPlayService.setRouterFragment(RouteFragment.this); mPlaylistAdapter.add(mMediaRouterPlayService.getPlaylist()); applyColors(); RouteInfo currentRoute = mMediaRouterPlayService.getCurrentRoute(); if (currentRoute != null) playlistMode(currentRoute); } public void onServiceDisconnected(ComponentName className) { mMediaRouterPlayService = null; } }; /** * Selects remote playback route category. */ public RouteFragment() { MediaRouteSelector mSelector = new MediaRouteSelector.Builder() .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK) .build(); setRouteSelector(mSelector); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.route_fragment, null); }; /** * Initializes views, connects to service, adds default route. */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mRouteAdapter = new RouteAdapter(getActivity()); mRouteAdapter.add(MediaRouter.getInstance(getActivity()).getRoutes()); mRouteAdapter.remove(MediaRouter.getInstance(getActivity()).getDefaultRoute()); mPlaylistAdapter = new FileArrayAdapter(getActivity()); mListView = (ListView) getView().findViewById(R.id.listview); mListView.setAdapter(mRouteAdapter); mListView.setOnItemClickListener(this); mListView.setOnScrollListener(this); mListView.setEmptyView(getView().findViewById(android.R.id.empty)); mControls = getView().findViewById(R.id.controls); mProgressBar = (SeekBar) getView().findViewById(R.id.progressBar); mProgressBar.setOnSeekBarChangeListener(this); mShuffle = (ImageButton) getView().findViewById(R.id.shuffle); mShuffle.setImageResource(R.drawable.ic_action_shuffle); mShuffle.setOnClickListener(this); ImageButton previous = (ImageButton) getView().findViewById(R.id.previous); previous.setImageResource(R.drawable.ic_action_previous); previous.setOnClickListener(this); ImageButton next = (ImageButton) getView().findViewById(R.id.next); next.setImageResource(R.drawable.ic_action_next); next.setOnClickListener(this); mRepeat = (ImageButton) getView().findViewById(R.id.repeat); mRepeat.setImageResource(R.drawable.ic_action_repeat); mRepeat.setOnClickListener(this); mPlayPause = (ImageButton) getView().findViewById(R.id.playpause); mPlayPause.setOnClickListener(this); mPlayPause.setImageResource(R.drawable.ic_action_play); mCurrentTimeView = (TextView) getView().findViewById(R.id.current_time); mTotalTimeView = (TextView) getView().findViewById(R.id.total_time); getActivity().getApplicationContext().startService( new Intent(getActivity(), MediaRouterPlayService.class)); getActivity().getApplicationContext().bindService( new Intent(getActivity(), MediaRouterPlayService.class), mPlayServiceConnection, Context.BIND_AUTO_CREATE ); if (savedInstanceState != null) mListView.onRestoreInstanceState(savedInstanceState.getParcelable("list_state")); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //outState.putBoolean("route_selected", mSelectedRoute != null); outState.putParcelable("list_state", mListView.onSaveInstanceState()); } @Override public void onDestroy() { super.onDestroy(); getActivity().getApplicationContext().unbindService(mPlayServiceConnection); } /** * Starts active route discovery (which is automatically stopped on * fragment stop by parent class). */ @Override public int onPrepareCallbackFlags() { return MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY | MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN; } @Override public Callback onCreateCallback() { return new MediaRouter.Callback() { @Override public void onRouteAdded(MediaRouter router, RouteInfo route) { for (int i = 0; i < mRouteAdapter.getCount(); i++) if (mRouteAdapter.getItem(i).getId().equals(route.getId())) { mRouteAdapter.remove(mRouteAdapter.getItem(i)); break; } mRouteAdapter.add(route); } @Override public void onRouteChanged(MediaRouter router, RouteInfo route) { mRouteAdapter.notifyDataSetChanged(); } @Override public void onRouteRemoved(MediaRouter router, RouteInfo route) { mRouteAdapter.remove(route); if (route.equals(mSelectedRoute)) { mPlaying = false; onBackPressed(); } } @Override public void onRouteSelected(MediaRouter router, RouteInfo route) { } @Override public void onRouteUnselected(MediaRouter router, RouteInfo route) { } @Override public void onRouteVolumeChanged(MediaRouter router, RouteInfo route) { } @Override public void onRoutePresentationDisplayChanged( MediaRouter router, RouteInfo route) { } @Override public void onProviderAdded(MediaRouter router, ProviderInfo provider) { } @Override public void onProviderRemoved(MediaRouter router, ProviderInfo provider) { } @Override public void onProviderChanged(MediaRouter router, ProviderInfo provider) { } }; } /** * Selects a route or starts playback (depending on current ListAdapter). */ @Override public void onItemClick(AdapterView<?> a, View v, final int position, long id) { if (mListView.getAdapter() == mRouteAdapter) playlistMode(mRouteAdapter.getItem(position)); else { mMediaRouterPlayService.play(position); changePlayPauseState(true); } } /** * Displays UPNP devices in the ListView. */ private void deviceListMode() { mControls.setVisibility(View.GONE); mListView.setAdapter(mRouteAdapter); disableTrackHighlight(); mSelectedRoute = null; TextView emptyView = (TextView) mListView.getEmptyView(); emptyView.setText(R.string.route_list_empty); } /** * Displays playlist for route in the ListView. */ private void playlistMode(RouteInfo route) { mSelectedRoute = route; mMediaRouterPlayService.selectRoute(mSelectedRoute); mListView.setAdapter(mPlaylistAdapter); mControls.setVisibility(View.VISIBLE); if (mStartPlayingOnSelect != -1) { mMediaRouterPlayService.play(mStartPlayingOnSelect); changePlayPauseState(true); mStartPlayingOnSelect = -1; } TextView emptyView = (TextView) mListView.getEmptyView(); emptyView.setText(R.string.playlist_empty); mListView.post(new Runnable() { @Override public void run() { scrollToCurrent(); } }); } /** * Sets colored background on the item that is currently playing. */ private void enableTrackHighlight() { if (mListView.getAdapter() == mRouteAdapter || mMediaRouterPlayService == null || !isVisible()) return; disableTrackHighlight(); mCurrentTrackView = mListView.getChildAt(mMediaRouterPlayService.getCurrentTrack() - mListView.getFirstVisiblePosition() + mListView.getHeaderViewsCount()); if (mCurrentTrackView != null) mCurrentTrackView.setBackgroundColor( getResources().getColor(R.color.currently_playing_background)); } /** * Removes highlight from the item that was last highlighted. */ private void disableTrackHighlight() { if (mCurrentTrackView != null) mCurrentTrackView.setBackgroundColor(Color.TRANSPARENT); } /** * Unselects current media renderer if one is selected (with dialog). */ @Override public boolean onBackPressed() { if (mListView.getAdapter() == mPlaylistAdapter) { if (mPlaying) new AlertDialog.Builder(getActivity()) .setMessage(R.string.exit_renderer) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mMediaRouterPlayService.stop(); changePlayPauseState(false); deviceListMode(); } }) .setNegativeButton(android.R.string.no, null) .show(); else deviceListMode(); return true; } return false; } /** * Plays/pauses playback on button click. */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.playpause: if (mPlaying) { mMediaRouterPlayService.pause(); changePlayPauseState(false); } else { mMediaRouterPlayService.resume(); scrollToCurrent(); changePlayPauseState(true); } break; case R.id.shuffle: mMediaRouterPlayService.toggleShuffleEnabled(); applyColors(); break; case R.id.previous: mPreviousTapCount++; Handler handler = new Handler(); Runnable r = new Runnable() { @Override public void run() { // Single tap. mPreviousTapCount = 0; mMediaRouterPlayService.play(mMediaRouterPlayService.getCurrentTrack()); changePlayPauseState(true); } }; if (mPreviousTapCount == 1) handler.postDelayed(r, ViewConfiguration.getDoubleTapTimeout()); else if(mPreviousTapCount == 2) { // Double tap. mPreviousTapCount = 0; mMediaRouterPlayService.playPrevious(); } break; case R.id.next: boolean stillPlaying = mMediaRouterPlayService.playNext(); changePlayPauseState(stillPlaying); break; case R.id.repeat: mMediaRouterPlayService.toggleRepeatEnabled(); applyColors(); break; } } /** * Enables or disables highlighting on shuffle/repeat buttons (depending * if they are enabled or disabled). */ private void applyColors() { int highlight = getResources().getColor(R.color.button_highlight); int transparent = getResources().getColor(android.R.color.transparent); mShuffle.setColorFilter((mMediaRouterPlayService.getShuffleEnabled()) ? highlight : transparent); mRepeat.setColorFilter((mMediaRouterPlayService.getRepeatEnabled()) ? highlight : transparent); } /** * Sends manual seek on progress bar to renderer. */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) mMediaRouterPlayService.seek(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } /** * Keeps track highlighting on the correct item while views are rebuilt. */ @Override public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) { enableTrackHighlight(); } @Override public void onScrollStateChanged(AbsListView arg0, int arg1) { enableTrackHighlight(); } public void increaseVolume() { mMediaRouterPlayService.increaseVolume(); } public void decreaseVolume() { mMediaRouterPlayService.decreaseVolume(); } /** * Applies the playlist and starts playing at position. */ public void play(List<Item> playlist, int start) { mPlaylistAdapter.clear(); mPlaylistAdapter.add(playlist); mMediaRouterPlayService.setPlaylist(playlist); if (mSelectedRoute != null) { mMediaRouterPlayService.play(start); changePlayPauseState(true); } else { Toast.makeText(getActivity(), R.string.select_route, Toast.LENGTH_SHORT) .show(); mStartPlayingOnSelect = start; } } /** * Generates a time string in the format mm:ss from a time value in seconds. * * @param time Time value in seconds (non-negative). * @return Formatted time string. */ private String generateTimeString(int time) { assert(time >= 0); int seconds = time % 60; int minutes = time / 60; if (minutes > 99) return "99:99"; else return Integer.toString(minutes) + ":" + ((seconds > 9) ? seconds : "0" + Integer.toString(seconds)); } /** * Receives information from MediaRouterPlayService about playback status. */ public void receivePlaybackStatus(MediaItemStatus status) { // Views may not exist if fragment was just created/destroyed. if (getView() == null) return; int currentTime = (int) status.getContentPosition() / 1000; int totalTime = (int) status.getContentDuration() / 1000; mCurrentTimeView.setText(generateTimeString(currentTime)); mTotalTimeView.setText(generateTimeString(totalTime)); mProgressBar.setProgress(currentTime); mProgressBar.setMax(totalTime); if (status.getPlaybackState() == MediaItemStatus.PLAYBACK_STATE_PLAYING || status.getPlaybackState() == MediaItemStatus.PLAYBACK_STATE_BUFFERING || status.getPlaybackState() == MediaItemStatus.PLAYBACK_STATE_PENDING) changePlayPauseState(true); else changePlayPauseState(false); if (mListView.getAdapter() == mPlaylistAdapter) enableTrackHighlight(); } /** * Changes the state of mPlayPause button to pause/resume according to * current playback state, also sets mPlaying. * * @param playing True if an item is currently being played, false otherwise. */ private void changePlayPauseState(boolean playing) { mPlaying = playing; if (mPlaying) { mPlayPause.setImageResource(R.drawable.ic_action_pause); mPlayPause.setContentDescription(getResources().getString(R.string.pause)); } else { mPlayPause.setImageResource(R.drawable.ic_action_play); mPlayPause.setContentDescription(getResources().getString(R.string.play)); } } /** * When in playlist mode, scrolls to the item that is currently playing. */ public void scrollToCurrent() { if (mMediaRouterPlayService != null) { mListView.smoothScrollToPosition( mMediaRouterPlayService.getCurrentTrack()); } } }
package com.jcwhatever.nucleus.utils.materials; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.jcwhatever.nucleus.utils.PreCon; import org.bukkit.Material; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Utility to filter and identify {@link org.bukkit.Material}'s by * property. */ public class Materials { Materials() {} private static Multimap<Material, MaterialProperty> _properties = MultimapBuilder.enumKeys(Material.class).hashSetValues().build(); private static Multimap<MaterialProperty, Material> _materialsByProperty = MultimapBuilder.hashKeys().enumSetValues(Material.class).build(); /** * Determine if a material has a property. * * @param material The {@link org.bukkit.Material} to check. * @param propertyName The name of the property to check. */ public static boolean hasProperty(Material material, String propertyName) { PreCon.notNull(material); PreCon.notNull(propertyName); return hasProperty(material, MaterialProperty.forLookup(propertyName)); } /** * Determine if a material has a property. * * @param material The {@link org.bukkit.Material} to check. * @param property The {@link MaterialProperty} to check. */ public static boolean hasProperty(Material material, MaterialProperty property) { PreCon.notNull(material); PreCon.notNull(property); return _properties.get(material).contains(property); } /** * Get all materials that match the specified properties. * * @param properties The {@link MaterialProperty}'s to check for. */ public static Set<Material> get(MaterialProperty... properties) { PreCon.notNull(properties); Set<Material> results = EnumSet.noneOf(Material.class); for (MaterialProperty property : properties) { Collection<Material> stored = _materialsByProperty.get(property); Iterator<Material> iterator = results.iterator(); while (iterator.hasNext()) { Material material = iterator.next(); if (!stored.contains(material)) iterator.remove(); } results.addAll(stored); } return results; } /** * Get all {@link MaterialProperty}'s of the specified {@link org.bukkit.Material}. * * @param material The material to check. */ public static Set<MaterialProperty> getProperties(Material material) { PreCon.notNull(material); Collection<MaterialProperty> stored = _properties.get(material); return new HashSet<>(stored); } /** * Removes {@link org.bukkit.Material}'s from the provided {@link java.util.Collection} that * have the specified {@link MaterialProperty}'s. * * <p>Requires the provided collections iterator to implement the remove method.</p> * * @param materials The collection of materials to modify. * @param properties The properties to remove from the collection. */ public static void remove(Collection<Material> materials, MaterialProperty... properties) { PreCon.notNull(materials); PreCon.notNull(properties); Iterator<Material> iterator = materials.iterator(); while (iterator.hasNext()) { Material material = iterator.next(); for (MaterialProperty property : properties) { if (hasProperty(material, property)) { iterator.remove(); break; } } } } /** * Determine if a material is transparent. * * <p>This is the transparency that allows the player to walk through * a block, not the visual transparency as in glass.</p> * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#TRANSPARENT */ public static boolean isTransparent(Material material) { return hasProperty(material, MaterialProperty.TRANSPARENT); } /** * Determine if a material is a surface. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#SURFACE */ public static boolean isSurface(Material material) { return hasProperty(material, MaterialProperty.SURFACE); } /** * Determine if a material is an openable boundary. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#OPENABLE_BOUNDARY */ public static boolean isOpenable(Material material) { return hasProperty(material, MaterialProperty.OPENABLE_BOUNDARY); } /** * Determine if a material is a door. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#DOOR */ public static boolean isDoor(Material material) { return hasProperty(material, MaterialProperty.DOOR); } /** * Determine if a material is a fence gate. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#FENCE_GATE */ public static boolean isFenceGate(Material material) { return hasProperty(material, MaterialProperty.FENCE_GATE); } /** * Determine if a material is a trap door. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#TRAPDOOR */ public static boolean isTrapDoor(Material material) { return hasProperty(material, MaterialProperty.TRAPDOOR); } /** * Determine if a material is redstone compatible. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#REDSTONE */ public static boolean isRedstoneCompatible(Material material) { return hasProperty(material, MaterialProperty.REDSTONE); } /** * Determine if a material activates a redstone current when interacted * with by a player. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#REDSTONE_SWITCH */ public static boolean isRedstoneSwitch(Material material) { return hasProperty(material, MaterialProperty.REDSTONE_SWITCH); } /** * Determine if a material is a button. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#BUTTON */ public static boolean isButton(Material material) { return hasProperty(material, MaterialProperty.BUTTON); } /** * Determine if a material is a pressure plate. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#PRESSURE_PLATE */ public static boolean isPressurePlate(Material material) { return hasProperty(material, MaterialProperty.PRESSURE_PLATE); } /** * Determine if a material is a lever. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#LEVER */ public static boolean isLever(Material material) { return hasProperty(material, MaterialProperty.LEVER); } /** * Determine if a material is leaves. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#LEAVES */ public static boolean isLeaves(Material material) { return hasProperty(material, MaterialProperty.LEAVES); } /** * Determine if a material is a log. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#LOG */ public static boolean isLog(Material material) { return hasProperty(material, MaterialProperty.LOG); } /** * Determine if a material is wearable by a player. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#WEARABLE */ public static boolean isWearable(Material material) { return hasProperty(material, MaterialProperty.WEARABLE); } /** * Determine if a material is player armor. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#ARMOR */ public static boolean isArmor(Material material) { return hasProperty(material, MaterialProperty.ARMOR); } /** * Determine if a material is a helmet. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#HELMET */ public static boolean isHelmet(Material material) { return hasProperty(material, MaterialProperty.HELMET); } /** * Determine if a material is a chestplate. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#CHESTPLATE */ public static boolean isChestplate(Material material) { return hasProperty(material, MaterialProperty.CHESTPLATE); } /** * Determine if a material is leggings. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#LEGGINGS */ public static boolean isLeggings(Material material) { return hasProperty(material, MaterialProperty.LEGGINGS); } /** * Determine if a material is boots. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#BOOTS */ public static boolean isBoots(Material material) { return hasProperty(material, MaterialProperty.BOOTS); } /** * Determine if a material is a weapon. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#WEAPON */ public static boolean isWeapon(Material material) { return hasProperty(material, MaterialProperty.WEAPON); } /** * Determine if a material is a tool. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#TOOL */ public static boolean isTool(Material material) { return hasProperty(material, MaterialProperty.TOOL); } /** * Determine if a material is a mining tool. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#MINING_TOOL */ public static boolean isMiningTool(Material material) { return hasProperty(material, MaterialProperty.MINING_TOOL); } /** * Determine if a material is a shovel. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#SHOVEL */ public static boolean isShovel(Material material) { return hasProperty(material, MaterialProperty.SHOVEL); } /** * Determine if a material is a hoe. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#HOE */ public static boolean isHoe(Material material) { return hasProperty(material, MaterialProperty.HOE); } /** * Determine if a material is an axe. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#AXE */ public static boolean isAxe(Material material) { return hasProperty(material, MaterialProperty.AXE); } /** * Determine if a material is a pickaxe. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#PICKAXE */ public static boolean isPickaxe(Material material) { return hasProperty(material, MaterialProperty.PICKAXE); } /** * Determine if a material is based on wood. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#WOOD_BASED */ public static boolean isWoodBased(Material material) { return hasProperty(material, MaterialProperty.WOOD_BASED); } /** * Determine if a material is based on stone. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#STONE_BASED */ public static boolean isStoneBased(Material material) { return hasProperty(material, MaterialProperty.STONE_BASED); } /** * Determine if a material is based on leather. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#LEATHER_BASED */ public static boolean isLeatherBased(Material material) { return hasProperty(material, MaterialProperty.LEATHER_BASED); } /** * Determine if a material is based on iron. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#IRON_BASED */ public static boolean isIronBased(Material material) { return hasProperty(material, MaterialProperty.IRON_BASED); } /** * Determine if a material is based on gold. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#GOLD_BASED */ public static boolean isGoldBased(Material material) { return hasProperty(material, MaterialProperty.GOLD_BASED); } /** * Determine if a material is based on diamond. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#DIAMOND_BASED */ public static boolean isDiamondBased(Material material) { return hasProperty(material, MaterialProperty.DIAMOND_BASED); } /** * Determine if a material is based on quartz. * * @param material The {@link org.bukkit.Material} to check. * @see MaterialProperty#QUARTZ_BASED */ public static boolean isQuartzBased(Material material) { return hasProperty(material, MaterialProperty.QUARTZ_BASED); } /** * Determine if a material can be placed by player. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#PLACEABLE */ public static boolean isPlaceable(Material material) { return hasProperty(material, MaterialProperty.PLACEABLE); } public static boolean isCraftable(Material material) { return hasProperty(material, MaterialProperty.CRAFTABLE); } /** * Determine if a material is a block. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#BLOCK */ public static boolean isBlock(Material material) { return hasProperty(material, MaterialProperty.BLOCK); } /** * Determine if a material is a multi-block. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#MULTI_BLOCK */ public static boolean isMultiBlock(Material material) { return hasProperty(material, MaterialProperty.MULTI_BLOCK); } /** * Determine if a material is stairs. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#STAIRS */ public static boolean isStairs(Material material) { return hasProperty(material, MaterialProperty.STAIRS); } /** * Determine if a material is an ore block. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#ORE */ public static boolean isOre(Material material) { return hasProperty(material, MaterialProperty.ORE); } /** * Determine if a material is repairable/damageable. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#REPAIRABLE */ public static boolean isRepairable(Material material) { return hasProperty(material, MaterialProperty.REPAIRABLE); } /** * Determine if a material can be thrown by a player. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#THROWABLE */ public static boolean isThrowable(Material material) { return hasProperty(material, MaterialProperty.THROWABLE); } /** * Determine if a material is consumable by a player. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#FOOD */ public static boolean isFood(Material material) { return hasProperty(material, MaterialProperty.FOOD); } /** * Determine if a material is a block that is affected * by gravity. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#GRAVITY */ public static boolean hasGravity(Material material) { return hasProperty(material, MaterialProperty.GRAVITY); } /** * Determine if a material has a GUI interface. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#GUI */ public static boolean hasGUI(Material material) { return hasProperty(material, MaterialProperty.GUI); } /** * Determine if a material has an inventory used to store items * for players. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#INVENTORY */ public static boolean hasInventory(Material material) { return hasProperty(material, MaterialProperty.INVENTORY); } /** * Determine if a materials byte meta data is used for color. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#MULTI_COLOR_DATA */ public static boolean hasColorData(Material material) { return hasProperty(material, MaterialProperty.MULTI_COLOR_DATA); } /** * Determine if a materials byte meta data is used to determine * the direction it faces. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#DIRECTIONAL_DATA */ public static boolean hasDirectionalData(Material material) { return hasProperty(material, MaterialProperty.DIRECTIONAL_DATA); } /** * Determine if a materials byte meta data is used to specify * a sub material. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#SUB_MATERIAL_DATA */ public static boolean hasSubMaterialData(Material material) { return hasProperty(material, MaterialProperty.SUB_MATERIAL_DATA); } /** * Determine if a materials durability data is used to specify * a sub material. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#SUB_MATERIAL_DURABILITY */ public static boolean hasSubMaterialDurability(Material material) { return hasProperty(material, MaterialProperty.SUB_MATERIAL_DURABILITY); } /** * Determine if a material can potentially be used as a potion ingredient. * * @param material The {@link org.bukkit.Material} to check. * * @see MaterialProperty#POTION_INGREDIENT */ public static boolean isPotionIngredient(Material material) { return hasProperty(material, MaterialProperty.POTION_INGREDIENT); } /** * Register custom {@link MaterialProperty}'s for the specified * {@link org.bukkit.Material}. * * @param material The {@link org.bukkit.Material}. * @param properties The {@link MaterialProperty}'s to register. */ public static void register(Material material, MaterialProperty... properties) { PreCon.notNull(material); if (properties == null || properties.length == 0) return; // make sure a default property type is not being registered. for (MaterialProperty property : properties) { if (property.isDefaultProperty()) { throw new IllegalArgumentException("Cannot register a default property type."); } } add(material, properties); } private static void add(Material material, MaterialProperty... properties) { _properties.putAll(material, Arrays.asList(properties)); for (MaterialProperty property : properties) { _materialsByProperty.put(property, material); } } static { add(Material.ACACIA_DOOR, MaterialProperty.BLOCK, MaterialProperty.MULTI_BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.REDSTONE); add(Material.ACACIA_DOOR_ITEM, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.ACACIA_FENCE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.ACACIA_FENCE_GATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.ACACIA_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.ACTIVATOR_RAIL, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.AIR, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.ANVIL, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.GUI, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE, MaterialProperty.REPAIRABLE); add(Material.APPLE, MaterialProperty.FOOD); add(Material.ARMOR_STAND, MaterialProperty.CRAFTABLE, MaterialProperty.PLACEABLE); // item add(Material.ARROW, MaterialProperty.THROWABLE, MaterialProperty.CRAFTABLE); add(Material.BAKED_POTATO, MaterialProperty.CRAFTABLE); add(Material.BANNER, MaterialProperty.CRAFTABLE, MaterialProperty.PLACEABLE); // item add(Material.BEACON, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.GUI, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.BED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.BED_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.BEDROCK, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.SURFACE); add(Material.BIRCH_DOOR, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.MULTI_BLOCK, MaterialProperty.REDSTONE); add(Material.BIRCH_DOOR_ITEM, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.BIRCH_FENCE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.BIRCH_FENCE_GATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.BIRCH_WOOD_STAIRS, MaterialProperty.BLOCK, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.BLAZE_POWDER, MaterialProperty.CRAFTABLE, MaterialProperty.POTION_INGREDIENT); add(Material.BOAT, MaterialProperty.CRAFTABLE); add(Material.BONE); add(Material.BOOK, MaterialProperty.CRAFTABLE); add(Material.BOOK_AND_QUILL, MaterialProperty.CRAFTABLE); add(Material.BOOKSHELF, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.BOW, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.BOWL, MaterialProperty.CRAFTABLE); add(Material.BREAD, MaterialProperty.CRAFTABLE); add(Material.BREWING_STAND, MaterialProperty.BLOCK, MaterialProperty.GUI); add(Material.BREWING_STAND_ITEM, MaterialProperty.PLACEABLE); add(Material.BRICK, MaterialProperty.CRAFTABLE); add(Material.BRICK_STAIRS, MaterialProperty.BLOCK, MaterialProperty.STAIRS, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.BROWN_MUSHROOM, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.BUCKET, MaterialProperty.CRAFTABLE); add(Material.BURNING_FURNACE, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.SURFACE); add(Material.CACTUS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.CAKE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.CAKE_BLOCK, MaterialProperty.SURFACE, MaterialProperty.BLOCK); add(Material.CARPET, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.CARROT, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.CARROT_ITEM, MaterialProperty.PLACEABLE); add(Material.CARROT_STICK, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.CRAFTABLE); add(Material.CAULDRON, MaterialProperty.BLOCK); add(Material.CAULDRON_ITEM, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.CHAINMAIL_BOOTS, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.ARMOR, MaterialProperty.BOOTS); add(Material.CHAINMAIL_CHESTPLATE, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.ARMOR, MaterialProperty.CHESTPLATE); add(Material.CHAINMAIL_HELMET, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.ARMOR, MaterialProperty.HELMET); add(Material.CHAINMAIL_LEGGINGS, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.ARMOR, MaterialProperty.LEGGINGS); add(Material.CHEST, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.CRAFTABLE); add(Material.CLAY, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.CLAY_BALL, MaterialProperty.CRAFTABLE); add(Material.CLAY_BRICK, MaterialProperty.CRAFTABLE); add(Material.COAL, MaterialProperty.SUB_MATERIAL_DATA); add(Material.COAL_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.COAL_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.COBBLE_WALL, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STONE_BASED, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.COBBLESTONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STONE_BASED, MaterialProperty.PLACEABLE); add(Material.COBBLESTONE_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.STONE_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.COCOA); add(Material.COMMAND, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.GUI); add(Material.COMMAND_MINECART); add(Material.COMPASS, MaterialProperty.CRAFTABLE); add(Material.COOKED_BEEF, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.COOKED_CHICKEN, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.COOKED_FISH, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.COOKED_MUTTON, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.COOKED_RABBIT, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.COOKIE, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.CROPS, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.DARK_OAK_DOOR, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.MULTI_BLOCK, MaterialProperty.REDSTONE); add(Material.DARK_OAK_DOOR_ITEM, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.DARK_OAK_FENCE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DARK_OAK_FENCE_GATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.DARK_OAK_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DAYLIGHT_DETECTOR, MaterialProperty.BLOCK, MaterialProperty.REDSTONE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DAYLIGHT_DETECTOR_INVERTED, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.DEAD_BUSH, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.DETECTOR_RAIL, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DIAMOND, MaterialProperty.DIAMOND_BASED); add(Material.DIAMOND_AXE, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.AXE, MaterialProperty.CRAFTABLE); add(Material.DIAMOND_BARDING, MaterialProperty.DIAMOND_BASED, MaterialProperty.HORSE_ARMOR); add(Material.DIAMOND_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.DIAMOND_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DIAMOND_BOOTS, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.BOOTS); add(Material.DIAMOND_CHESTPLATE, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.CHESTPLATE); add(Material.DIAMOND_HELMET, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.HELMET); add(Material.DIAMOND_HOE, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.HOE, MaterialProperty.CRAFTABLE); add(Material.DIAMOND_LEGGINGS, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.LEGGINGS); add(Material.DIAMOND_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.DIAMOND_BASED, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.DIAMOND_PICKAXE, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.PICKAXE, MaterialProperty.CRAFTABLE); add(Material.DIAMOND_SPADE, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.SHOVEL, MaterialProperty.CRAFTABLE); add(Material.DIAMOND_SWORD, MaterialProperty.DIAMOND_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.DIODE, MaterialProperty.REDSTONE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.DIODE_BLOCK_OFF, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.DIODE_BLOCK_ON, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.DIRT, MaterialProperty.BLOCK, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.SURFACE); add(Material.DISPENSER, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE, MaterialProperty.SURFACE); add(Material.DOUBLE_PLANT, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.MULTI_BLOCK, MaterialProperty.SUB_MATERIAL_DATA); add(Material.DOUBLE_STEP, MaterialProperty.BLOCK, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.SURFACE); add(Material.DRAGON_EGG); add(Material.DROPPER, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE, MaterialProperty.SURFACE); add(Material.EGG, MaterialProperty.THROWABLE); add(Material.EMERALD); add(Material.EMERALD_BLOCK, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.EMERALD_ORE, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.ORE, MaterialProperty.SURFACE); add(Material.EMPTY_MAP); add(Material.ENCHANTED_BOOK); add(Material.ENCHANTMENT_TABLE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.GUI); add(Material.ENDER_CHEST, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.SURFACE); add(Material.ENDER_PEARL, MaterialProperty.THROWABLE); add(Material.ENDER_PORTAL, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.ENDER_PORTAL_FRAME, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.ENDER_STONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.EXP_BOTTLE, MaterialProperty.THROWABLE); add(Material.EXPLOSIVE_MINECART); add(Material.EYE_OF_ENDER); add(Material.FEATHER); add(Material.FENCE, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.CRAFTABLE); add(Material.FENCE_GATE, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.CRAFTABLE); add(Material.FERMENTED_SPIDER_EYE, MaterialProperty.POTION_INGREDIENT); add(Material.FIRE, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.FIREBALL, MaterialProperty.THROWABLE); add(Material.FIREWORK, MaterialProperty.CRAFTABLE); add(Material.FIREWORK_CHARGE, MaterialProperty.CRAFTABLE); add(Material.FISHING_ROD, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.CRAFTABLE); add(Material.FLINT); add(Material.FLINT_AND_STEEL, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.CRAFTABLE); add(Material.FLOWER_POT, MaterialProperty.BLOCK); add(Material.FLOWER_POT_ITEM, MaterialProperty.PLACEABLE); add(Material.FURNACE, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.GUI, MaterialProperty.SURFACE); add(Material.GHAST_TEAR, MaterialProperty.POTION_INGREDIENT); add(Material.GLASS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.GLASS_BOTTLE, MaterialProperty.CRAFTABLE); add(Material.GLOWING_REDSTONE_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.GLOWSTONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.GLOWSTONE_DUST, MaterialProperty.POTION_INGREDIENT); add(Material.GOLD_AXE, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.AXE, MaterialProperty.CRAFTABLE); add(Material.GOLD_BARDING, MaterialProperty.GOLD_BASED, MaterialProperty.HORSE_ARMOR); add(Material.GOLD_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.GOLD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.GOLD_BOOTS, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.BOOTS); add(Material.GOLD_CHESTPLATE, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.CHESTPLATE); add(Material.GOLD_HELMET, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.HELMET); add(Material.GOLD_HOE, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.HOE, MaterialProperty.CRAFTABLE); add(Material.GOLD_INGOT, MaterialProperty.GOLD_BASED, MaterialProperty.CRAFTABLE); add(Material.GOLD_LEGGINGS, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.LEGGINGS); add(Material.GOLD_NUGGET, MaterialProperty.GOLD_BASED, MaterialProperty.CRAFTABLE); add(Material.GOLD_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.GOLD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.GOLD_PICKAXE, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.PICKAXE, MaterialProperty.CRAFTABLE); add(Material.GOLD_PLATE, MaterialProperty.BLOCK, MaterialProperty.GOLD_BASED, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.PRESSURE_PLATE, MaterialProperty.CRAFTABLE); add(Material.GOLD_RECORD); add(Material.GOLD_SPADE, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.SHOVEL, MaterialProperty.CRAFTABLE); add(Material.GOLD_SWORD, MaterialProperty.GOLD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.GOLDEN_APPLE, MaterialProperty.GOLD_BASED, MaterialProperty.FOOD, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.CRAFTABLE); add(Material.GOLDEN_CARROT, MaterialProperty.GOLD_BASED, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE, MaterialProperty.POTION_INGREDIENT); add(Material.GRASS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.GRAVEL, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.GRAVITY, MaterialProperty.PLACEABLE); add(Material.GREEN_RECORD); add(Material.GRILLED_PORK, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.HARD_CLAY, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.HAY_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.HOPPER, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.CRAFTABLE); add(Material.HOPPER_MINECART); add(Material.HUGE_MUSHROOM_1, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.HUGE_MUSHROOM_2, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.ICE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.INK_SACK, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.SUB_MATERIAL_DATA); add(Material.IRON_AXE, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.AXE, MaterialProperty.CRAFTABLE); add(Material.IRON_BARDING, MaterialProperty.IRON_BASED, MaterialProperty.HORSE_ARMOR); add(Material.IRON_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.IRON_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.IRON_BOOTS, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.BOOTS); add(Material.IRON_CHESTPLATE, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.CHESTPLATE); add(Material.IRON_DOOR, MaterialProperty.IRON_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.IRON_DOOR_BLOCK, MaterialProperty.BLOCK, MaterialProperty.MULTI_BLOCK, MaterialProperty.IRON_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.BLOCK, MaterialProperty.REDSTONE); add(Material.IRON_FENCE, MaterialProperty.BLOCK, MaterialProperty.IRON_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.IRON_HELMET, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.HELMET); add(Material.IRON_HOE, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.HOE, MaterialProperty.CRAFTABLE); add(Material.IRON_INGOT, MaterialProperty.IRON_BASED, MaterialProperty.CRAFTABLE); add(Material.IRON_LEGGINGS, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.LEGGINGS); add(Material.IRON_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.IRON_BASED, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.IRON_PICKAXE, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.PICKAXE, MaterialProperty.CRAFTABLE); add(Material.IRON_PLATE, MaterialProperty.BLOCK, MaterialProperty.IRON_BASED, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.PRESSURE_PLATE, MaterialProperty.CRAFTABLE); add(Material.IRON_SPADE, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.SHOVEL, MaterialProperty.CRAFTABLE); add(Material.IRON_SWORD, MaterialProperty.IRON_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.IRON_TRAPDOOR, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.IRON_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.TRAPDOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.ITEM_FRAME, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.JACK_O_LANTERN, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.WEARABLE); add(Material.JUKEBOX, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.JUNGLE_DOOR, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.MULTI_BLOCK, MaterialProperty.REDSTONE); add(Material.JUNGLE_DOOR_ITEM, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.JUNGLE_FENCE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.JUNGLE_FENCE_GATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.JUNGLE_WOOD_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.LADDER, MaterialProperty.BLOCK, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.LAPIS_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.LAPIS_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.LAVA, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE); add(Material.LAVA_BUCKET); add(Material.LEASH); add(Material.LEATHER, MaterialProperty.LEATHER_BASED); add(Material.LEATHER_BOOTS, MaterialProperty.LEATHER_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.BOOTS); add(Material.LEATHER_CHESTPLATE, MaterialProperty.LEATHER_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.CHESTPLATE); add(Material.LEATHER_HELMET, MaterialProperty.LEATHER_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.HELMET); add(Material.LEATHER_LEGGINGS, MaterialProperty.LEATHER_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEARABLE, MaterialProperty.CRAFTABLE, MaterialProperty.ARMOR, MaterialProperty.LEGGINGS); add(Material.LEAVES, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.LEAVES); add(Material.LEAVES_2, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.LEAVES); add(Material.LEVER, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.LEVER, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.LOG, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.LOG); add(Material.LOG_2, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.LOG); add(Material.LONG_GRASS, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.SUB_MATERIAL_DATA); add(Material.MAGMA_CREAM, MaterialProperty.POTION_INGREDIENT); add(Material.MAP); add(Material.MELON); add(Material.MELON_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.MELON_SEEDS); add(Material.MELON_STEM); add(Material.MILK_BUCKET); add(Material.MINECART, MaterialProperty.CRAFTABLE); add(Material.MOB_SPAWNER); add(Material.MONSTER_EGG); add(Material.MONSTER_EGGS); add(Material.MOSSY_COBBLESTONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STONE_BASED, MaterialProperty.PLACEABLE); add(Material.MUSHROOM_SOUP, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.MUTTON, MaterialProperty.FOOD); add(Material.MYCEL, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.NAME_TAG); add(Material.NETHER_BRICK, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.NETHER_BRICK_ITEM, MaterialProperty.PLACEABLE); add(Material.NETHER_BRICK_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.NETHER_FENCE, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.NETHER_STALK, MaterialProperty.POTION_INGREDIENT); // Nether wart item add(Material.NETHER_STAR); add(Material.NETHER_WARTS, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.NETHERRACK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK); add(Material.NOTE_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.OBSIDIAN, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.PACKED_ICE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.PAINTING, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.PAPER, MaterialProperty.CRAFTABLE); add(Material.PISTON_BASE, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.PISTON_EXTENSION); add(Material.PISTON_MOVING_PIECE); add(Material.PISTON_STICKY_BASE, MaterialProperty.SURFACE); add(Material.POISONOUS_POTATO, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.PORK, MaterialProperty.FOOD); add(Material.PORTAL, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.POTATO, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.POTATO_ITEM, MaterialProperty.FOOD); add(Material.POTION, MaterialProperty.THROWABLE, MaterialProperty.POTION_INGREDIENT, MaterialProperty.SUB_MATERIAL_DURABILITY); add(Material.POWERED_MINECART); add(Material.POWERED_RAIL, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.PRISMARINE); add(Material.PRISMARINE_CRYSTALS); add(Material.PRISMARINE_SHARD); add(Material.PUMPKIN, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.PUMPKIN_PIE, MaterialProperty.CRAFTABLE); add(Material.PUMPKIN_SEEDS); add(Material.PUMPKIN_STEM); add(Material.QUARTZ, MaterialProperty.QUARTZ_BASED); add(Material.QUARTZ_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.QUARTZ_BASED, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.QUARTZ_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.QUARTZ_BASED, MaterialProperty.PLACEABLE, MaterialProperty.ORE); add(Material.QUARTZ_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.QUARTZ_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.RABBIT); add(Material.RABBIT_FOOT, MaterialProperty.POTION_INGREDIENT); add(Material.RABBIT_HIDE); add(Material.RABBIT_STEW, MaterialProperty.FOOD, MaterialProperty.CRAFTABLE); add(Material.RAILS, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.RAW_BEEF, MaterialProperty.FOOD); add(Material.RAW_CHICKEN, MaterialProperty.FOOD); add(Material.RAW_FISH, MaterialProperty.FOOD, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.POTION_INGREDIENT); add(Material.RECORD_10); add(Material.RECORD_11); add(Material.RECORD_12); add(Material.RECORD_3); add(Material.RECORD_4); add(Material.RECORD_5); add(Material.RECORD_6); add(Material.RECORD_7); add(Material.RECORD_8); add(Material.RECORD_9); add(Material.RED_MUSHROOM, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.RED_ROSE, MaterialProperty.BLOCK, MaterialProperty.PLACEABLE, MaterialProperty.TRANSPARENT, MaterialProperty.SUB_MATERIAL_DATA); add(Material.RED_SANDSTONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.CRAFTABLE); add(Material.RED_SANDSTONE_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.REDSTONE, MaterialProperty.PLACEABLE, MaterialProperty.POTION_INGREDIENT); add(Material.REDSTONE_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.REDSTONE_COMPARATOR, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.REDSTONE_COMPARATOR_OFF, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.REDSTONE_COMPARATOR_ON, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.REDSTONE_LAMP_OFF, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.REDSTONE_LAMP_ON, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.REDSTONE); add(Material.REDSTONE_ORE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.REDSTONE_TORCH_OFF, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.REDSTONE_TORCH_ON, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.REDSTONE_WIRE, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE); add(Material.ROTTEN_FLESH, MaterialProperty.FOOD); add(Material.SADDLE); add(Material.SAND, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.GRAVITY); add(Material.SANDSTONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SANDSTONE_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SAPLING, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE); add(Material.SEA_LANTERN, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SEEDS, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE); add(Material.SHEARS, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.CRAFTABLE); add(Material.SIGN, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SIGN_POST, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.SKULL, MaterialProperty.BLOCK); add(Material.SKULL_ITEM, MaterialProperty.PLACEABLE, MaterialProperty.WEARABLE); add(Material.SLIME_BALL); add(Material.SMOOTH_BRICK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SMOOTH_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SNOW, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.SNOW_BALL, MaterialProperty.THROWABLE); add(Material.SNOW_BLOCK, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SOIL, MaterialProperty.BLOCK, MaterialProperty.SURFACE); add(Material.SOUL_SAND, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.SPECKLED_MELON, MaterialProperty.POTION_INGREDIENT); // Glistering Melon add(Material.SPIDER_EYE, MaterialProperty.POTION_INGREDIENT); add(Material.SPONGE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.PLACEABLE); add(Material.SPRUCE_DOOR, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.MULTI_BLOCK, MaterialProperty.REDSTONE); add(Material.SPRUCE_DOOR_ITEM, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.SPRUCE_FENCE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.SPRUCE_FENCE_GATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.FENCE_GATE, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.CRAFTABLE, MaterialProperty.REDSTONE); add(Material.SPRUCE_WOOD_STAIRS, MaterialProperty.BLOCK, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.BLOCK, MaterialProperty.CRAFTABLE, MaterialProperty.SURFACE); add(Material.STAINED_CLAY, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.CRAFTABLE); add(Material.STAINED_GLASS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.CRAFTABLE); add(Material.STAINED_GLASS_PANE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.CRAFTABLE); add(Material.STANDING_BANNER, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.STATIONARY_LAVA, MaterialProperty.BLOCK); add(Material.STATIONARY_WATER, MaterialProperty.BLOCK); add(Material.STEP, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.CRAFTABLE); add(Material.STICK); add(Material.STONE, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STONE_BASED, MaterialProperty.PLACEABLE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.CRAFTABLE); add(Material.STONE_AXE, MaterialProperty.STONE_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.AXE, MaterialProperty.CRAFTABLE); add(Material.STONE_BUTTON, MaterialProperty.BLOCK, MaterialProperty.STONE_BASED, MaterialProperty.PLACEABLE, MaterialProperty.TRANSPARENT, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.BUTTON, MaterialProperty.CRAFTABLE); add(Material.STONE_HOE, MaterialProperty.STONE_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.HOE, MaterialProperty.CRAFTABLE); add(Material.STONE_PICKAXE, MaterialProperty.STONE_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.PICKAXE, MaterialProperty.CRAFTABLE); add(Material.STONE_PLATE, MaterialProperty.BLOCK, MaterialProperty.STONE_BASED, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.PRESSURE_PLATE, MaterialProperty.CRAFTABLE); add(Material.STONE_SLAB2, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STONE_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.STONE_SPADE, MaterialProperty.STONE_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.SHOVEL, MaterialProperty.CRAFTABLE); add(Material.STONE_SWORD, MaterialProperty.STONE_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.STORAGE_MINECART); add(Material.STRING); add(Material.SUGAR, MaterialProperty.POTION_INGREDIENT); add(Material.SUGAR_CANE, MaterialProperty.PLACEABLE); add(Material.SUGAR_CANE_BLOCK, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.BLOCK); add(Material.SULPHUR, MaterialProperty.POTION_INGREDIENT); // gunpowder add(Material.THIN_GLASS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.TNT, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.TORCH, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.TRAP_DOOR, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.TRAPDOOR, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.TRAPPED_CHEST, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.INVENTORY, MaterialProperty.GUI, MaterialProperty.CRAFTABLE); add(Material.TRIPWIRE, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.TRIPWIRE_HOOK, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.VINE, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.WALL_BANNER, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.WALL_SIGN, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); add(Material.WATCH, MaterialProperty.CRAFTABLE); add(Material.WATER, MaterialProperty.BLOCK); add(Material.WATER_BUCKET); add(Material.WATER_LILY, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE); add(Material.WEB, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.WHEAT, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE); add(Material.WOOD, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.SUB_MATERIAL_DATA, MaterialProperty.WOOD_BASED, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.WOOD_AXE, MaterialProperty.REPAIRABLE, MaterialProperty.WOOD_BASED, MaterialProperty.TOOL, MaterialProperty.AXE, MaterialProperty.CRAFTABLE); add(Material.WOOD_BUTTON, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.WOOD_BASED, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.BUTTON, MaterialProperty.CRAFTABLE); add(Material.WOOD_DOOR, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.WOOD_BASED, MaterialProperty.DOOR, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.CRAFTABLE); add(Material.WOOD_DOUBLE_STEP, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.WOOD_BASED, MaterialProperty.SUB_MATERIAL_DATA); add(Material.WOOD_HOE, MaterialProperty.WOOD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.HOE, MaterialProperty.CRAFTABLE); add(Material.WOOD_PICKAXE, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.PICKAXE, MaterialProperty.CRAFTABLE); add(Material.WOOD_PLATE, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.TRANSPARENT, MaterialProperty.PLACEABLE, MaterialProperty.REDSTONE, MaterialProperty.REDSTONE_SWITCH, MaterialProperty.PRESSURE_PLATE, MaterialProperty.CRAFTABLE); add(Material.WOOD_SPADE, MaterialProperty.WOOD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.TOOL, MaterialProperty.MINING_TOOL, MaterialProperty.SHOVEL, MaterialProperty.CRAFTABLE); add(Material.WOOD_STAIRS, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.STAIRS, MaterialProperty.WOOD_BASED, MaterialProperty.DIRECTIONAL_DATA, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE); add(Material.WOOD_STEP, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.WOOD_BASED, MaterialProperty.SUB_MATERIAL_DATA); add(Material.WOOD_SWORD, MaterialProperty.WOOD_BASED, MaterialProperty.REPAIRABLE, MaterialProperty.WEAPON, MaterialProperty.CRAFTABLE); add(Material.WOODEN_DOOR, MaterialProperty.BLOCK, MaterialProperty.WOOD_BASED, MaterialProperty.OPENABLE_BOUNDARY, MaterialProperty.DOOR, MaterialProperty.MULTI_BLOCK, MaterialProperty.REDSTONE);// block add(Material.WOOL, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.MULTI_COLOR_DATA, MaterialProperty.CRAFTABLE); add(Material.WORKBENCH, MaterialProperty.BLOCK, MaterialProperty.SURFACE, MaterialProperty.PLACEABLE, MaterialProperty.CRAFTABLE, MaterialProperty.GUI); add(Material.WRITTEN_BOOK, MaterialProperty.GUI); add(Material.YELLOW_FLOWER, MaterialProperty.BLOCK, MaterialProperty.TRANSPARENT); } }
package com.mebigfatguy.patchanim.gui; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.EnumSet; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import com.mebigfatguy.patchanim.AnimationType; import com.mebigfatguy.patchanim.OutOfBoundsColor; import com.mebigfatguy.patchanim.PatchAnimDocument; import com.mebigfatguy.patchanim.TweenStyle; import com.mebigfatguy.patchanim.gui.events.DocumentChangedEvent; import com.mebigfatguy.patchanim.gui.events.DocumentChangedListener; import com.mebigfatguy.patchanim.main.PatchAnimBundle; public class JPatchControlPanel extends JPanel { private static final long serialVersionUID = -5968231995166721151L; private PatchAnimDocument document; private JTextField widthField; private JTextField heightField; private JComboBox animationCB; private JComboBox outOfBoundsColorCB; private JTextField tweenFramesField; private JComboBox tweenStyleCB; private JButton testButton; public JPatchControlPanel() { initComponents(); initListeners(); } private void initComponents() { ResourceBundle rb = PatchAnimBundle.getBundle(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createTitledBorder(rb.getString(PatchAnimBundle.CONTROLS))); JLabel widthLabel; JLabel heightLabel; JLabel animationLabel; JLabel outOfBoundsLabel; JLabel tweenFramesLabel; JLabel tweenStyleLabel; { widthLabel = new JLabel(rb.getString(PatchAnimBundle.WIDTH)); widthField = new JTextField(new IntegerDocument(), "", 8); widthLabel.setLabelFor(widthField); widthField.setToolTipText(rb.getString(PatchAnimBundle.WIDTH_TT)); JPanel p = Utils.createFormPanel(widthLabel, widthField); Utils.limitPanelHeight(p, widthField); add(p); } add(Box.createVerticalStrut(5)); { heightLabel = new JLabel(rb.getString(PatchAnimBundle.HEIGHT)); heightField = new JTextField(new IntegerDocument(), "", 8); heightLabel.setLabelFor(heightField); heightField.setToolTipText(rb.getString(PatchAnimBundle.HEIGHT_TT)); JPanel p = Utils.createFormPanel(heightLabel, heightField); Utils.limitPanelHeight(p, heightField); add(p); } add(Box.createVerticalStrut(5)); { animationLabel = new JLabel(rb.getString(PatchAnimBundle.ANIMATION)); animationCB = new JComboBox(new Object[] { AnimationType.None, AnimationType.Cycle, AnimationType.Wave }); animationLabel.setLabelFor(animationCB); animationCB.setToolTipText(rb.getString(PatchAnimBundle.ANIMATION_TT)); JPanel p = Utils.createFormPanel(animationLabel, animationCB); Utils.limitPanelHeight(p, animationCB); add(p); } add(Box.createVerticalStrut(5)); { outOfBoundsLabel = new JLabel(rb.getString(PatchAnimBundle.OUTOFBOUNDSCOLOR)); outOfBoundsColorCB = new JComboBox(new Object[] { OutOfBoundsColor.Clip, OutOfBoundsColor.Cycle, OutOfBoundsColor.Wave }); outOfBoundsColorCB.setToolTipText(rb.getString(PatchAnimBundle.OUTOFBOUNDSCOLOR_TT)); outOfBoundsLabel.setLabelFor(outOfBoundsColorCB); JPanel p = Utils.createFormPanel(outOfBoundsLabel, outOfBoundsColorCB); Utils.limitPanelHeight(p, outOfBoundsColorCB); add(p); } add(Box.createVerticalStrut(5)); { tweenFramesLabel = new JLabel(rb.getString(PatchAnimBundle.TWEENFRAMES)); tweenFramesField = new JTextField(new IntegerDocument(), "", 8); tweenFramesLabel.setLabelFor(tweenFramesField); tweenFramesField.setToolTipText(rb.getString(PatchAnimBundle.TWEENFRAMES_TT)); JPanel p = Utils.createFormPanel(tweenFramesLabel, tweenFramesField); Utils.limitPanelHeight(p, tweenFramesField); add(p); } add(Box.createVerticalStrut(5)); { tweenStyleLabel = new JLabel(rb.getString(PatchAnimBundle.TWEENSTYLE)); EnumSet<TweenStyle> ts = EnumSet.<TweenStyle>allOf(TweenStyle.class); tweenStyleCB = new JComboBox(ts.toArray(new TweenStyle[ts.size()])); tweenStyleLabel.setLabelFor(tweenStyleCB); tweenStyleCB.setToolTipText(rb.getString(PatchAnimBundle.TWEENSTYLE_TT)); outOfBoundsLabel.setLabelFor(tweenStyleCB); JPanel p = Utils.createFormPanel(tweenStyleLabel, tweenStyleCB); Utils.limitPanelHeight(p, tweenStyleCB); add(p); } add(Box.createVerticalStrut(5)); testButton = new JButton(rb.getString(PatchAnimBundle.TEST)); testButton.setToolTipText(rb.getString(PatchAnimBundle.TEST_TT)); add(testButton); Utils.sizeUniformly(Utils.Sizing.Both, widthLabel, heightLabel, animationLabel, outOfBoundsLabel, tweenFramesLabel, tweenStyleLabel); Utils.sizeUniformly(Utils.Sizing.Width, new JComponent[] { widthField, heightField, animationCB, outOfBoundsColorCB, tweenFramesField, tweenStyleCB }); add(Box.createVerticalGlue()); Dimension d = getPreferredSize(); if (d.width < 200) d.width = 200; setPreferredSize(d); } private void initListeners() { PatchPanelMediator mediator = PatchPanelMediator.getMediator(); mediator.addDocumentChangedListener(new DocumentChangedListener() { public void documentChanged(DocumentChangedEvent dce) { document = dce.getDocument(); SwingUtilities.invokeLater(new Runnable() { public void run() { widthField.setText(String.valueOf(document.getWidth())); heightField.setText(String.valueOf(document.getHeight())); animationCB.setSelectedIndex(document.getAnimationType().ordinal()); outOfBoundsColorCB.setSelectedIndex(document.getOutOfBoundsColor().ordinal()); tweenFramesField.setText(String.valueOf(document.getTweenCount())); tweenStyleCB.setSelectedIndex(document.getTweenStyle().ordinal()); } }); } }); widthField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent fe) { try { int oldWidth = document.getWidth(); int newWidth = Integer.parseInt(widthField.getText()); if (oldWidth != newWidth) { document.setWidth(newWidth); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } catch (NumberFormatException nfe) { document.setWidth(100); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } public void focusGained(FocusEvent fe) { widthField.setSelectionStart(0); widthField.setSelectionEnd(Integer.MAX_VALUE); } }); heightField.addFocusListener(new FocusListener() { public void focusLost(FocusEvent arg0) { try { int oldHeight = document.getHeight(); int newHeight = Integer.parseInt(heightField.getText()); if (oldHeight != newHeight) { document.setHeight(newHeight); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } catch (NumberFormatException nfe) { document.setHeight(100); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } public void focusGained(FocusEvent fe) { heightField.setSelectionStart(0); heightField.setSelectionEnd(Integer.MAX_VALUE); } }); tweenFramesField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent arg0) { try { int oldTween = document.getTweenCount(); int newTween = Integer.parseInt(tweenFramesField.getText()); if (oldTween != newTween) { document.setTweenCount(newTween); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } catch (NumberFormatException nfe) { document.setTweenCount(10); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } }); animationCB.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { document.setAnimationType((AnimationType)ie.getItem()); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } }); outOfBoundsColorCB.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { document.setOutOfBoundsColor((OutOfBoundsColor)ie.getItem()); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } }); tweenFramesField.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent fe) { tweenFramesField.setSelectionStart(0); tweenFramesField.setSelectionEnd(Integer.MAX_VALUE); } }); tweenStyleCB.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (ie.getStateChange() == ItemEvent.SELECTED) { document.setTweenStyle((TweenStyle)ie.getItem()); PatchPanelMediator ppMediator = PatchPanelMediator.getMediator(); ppMediator.fireSettingsChanged(); } } }); testButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JTestFrame tf = new JTestFrame(); tf.setLocationRelativeTo(JPatchControlPanel.this.getRootPane()); tf.setVisible(true); tf.setAlwaysOnTop(true); tf.beginAnimation(); } }); } }
package com.obidea.semantika.cli2.command; public class CommandFactory { public static Command create(String command) throws Exception { if (startsWith(command, Command.SELECT)) { return new SelectCommand(command); } else if (startsWith(command, Command.SET_PREFIX)) { return new SetPrefixCommand(command); } else if (startsWith(command, Command.SHOW_PREFIXES)) { return new ShowPrefixesCommand(command); } throw new Exception("Unknown command"); //$NON-NLS-1$ } private static boolean startsWith(String command, String keyword) { return command.startsWith(keyword) || command.startsWith(keyword.toUpperCase()); } }
package com.reason.ide.hints; import com.intellij.lang.Language; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.util.containers.Stack; import com.reason.Joiner; import com.reason.lang.core.signature.ORSignature; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.Set; public class InferredTypesImplementation implements InferredTypes { private static final String OPEN = "Op"; private static final String MODULE_GHOST = "Mg"; private static final String VALUE = "Va"; private static final String IDENT = "Id"; private final Map<String, Stack<OpenModule>> m_opens = new THashMap<>(); private final Map<Integer, LogicalORSignature> m_vals = new THashMap<>(); private final Map<LogicalPosition, ORSignature> m_idents = new THashMap<>(); @NotNull public Map<Integer, String> signaturesByLines(Language lang) { Map<Integer, String> result = new THashMap<>(); for (Stack<OpenModule> openStack : m_opens.values()) { for (OpenModule openModule : openStack) { String exposing = openModule.getExposing(); if (exposing != null) { result.put(openModule.getLine(), exposing); } } } for (Map.Entry<Integer, LogicalORSignature> entry : m_vals.entrySet()) { result.put(entry.getKey(), entry.getValue().getSignature().asString(lang)); } return result; } @NotNull public Map<LogicalPosition, ORSignature> typesByIdents() { return m_idents; } public void add(@NotNull String entry, @NotNull LogicalPosition start, @NotNull LogicalPosition end, @NotNull String line) { if (OPEN.equals(entry)) { // Pattern :: Name Stack<OpenModule> openStack = m_opens.get(line); if (openStack == null) { openStack = new Stack<>(); m_opens.put(line, openStack); } openStack.push(new OpenModule(start, end)); } else if (VALUE.equals(entry)) { // Pattern :: Name|type String[] tokens = line.split("\\|", 2); addVisibleSignature(start, new ORSignature(tokens[1])); } else if (MODULE_GHOST.equals(entry)) { // Pattern :: name|type String[] tokens = line.split("\\|", 2); String signature = tokens[1].startsWith("type t = ") ? tokens[1].substring(9) : tokens[1]; addVisibleSignature(start, new ORSignature(signature)); } else if (IDENT.equals(entry)) { // Pattern :: name|qname|type String[] tokens = line.split("\\|", 3); m_idents.put(start, new ORSignature(tokens[2])); if (!tokens[0].equals(tokens[1])) { int lastDot = tokens[1].lastIndexOf("."); if (0 < lastDot) { String path = tokens[1].substring(0, lastDot); Stack<OpenModule> openStack = m_opens.get(path); if (openStack != null) { openStack.peek().addId(tokens[0]); } } } } } private void addVisibleSignature(@NotNull LogicalPosition pos, @NotNull ORSignature signature) { LogicalORSignature savedSignature = m_vals.get(pos.line); if (savedSignature == null || pos.column < savedSignature.getLogicalPosition().column) { m_vals.put(pos.line, new LogicalORSignature(pos, signature)); } } static class OpenModule { @NotNull private final LogicalPosition m_position; private final Set<String> m_values = new THashSet<>(); OpenModule(LogicalPosition start, LogicalPosition end) { m_position = start; } Integer getLine() { return m_position.line; } @Nullable String getExposing() { return m_values.isEmpty() ? null : "exposing: " + Joiner.join(", ", m_values); } void addId(String id) { m_values.add(id); } } static class LogicalORSignature { @NotNull private final LogicalPosition m_logicalPosition; @NotNull private final ORSignature m_signature; LogicalORSignature(@NotNull LogicalPosition position, @NotNull ORSignature signature) { m_logicalPosition = position; m_signature = signature; } @NotNull LogicalPosition getLogicalPosition() { return m_logicalPosition; } @NotNull public ORSignature getSignature() { return m_signature; } } }
package com.redhat.ceylon.compiler.typechecker.tree; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError; import com.redhat.ceylon.compiler.typechecker.analyzer.UnsupportedError; import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning; import com.redhat.ceylon.compiler.typechecker.context.TypecheckerUnit; import com.redhat.ceylon.compiler.typechecker.parser.LexError; import com.redhat.ceylon.compiler.typechecker.parser.ParseError; import com.redhat.ceylon.compiler.typechecker.util.PrintVisitor; import com.redhat.ceylon.model.typechecker.model.Scope; public abstract class Node { private String text; private Token token; private Token endToken; private Token firstChildToken; private Token lastChildToken; private Scope scope; private TypecheckerUnit unit; private List<Message> errors = null; protected Node(Token token) { this.token = token; } /** * The scope within which the node occurs. */ public Scope getScope() { return scope; } public void setScope(Scope scope) { this.scope = scope; } /** * The compilation unit in which the node * occurs. */ public TypecheckerUnit getUnit() { return unit; } public void setUnit(TypecheckerUnit unit) { this.unit = unit; } /** * The text of the corresponding ANTLR node. */ public String getText() { if (text!=null) { return text; } else if (token==null) { return ""; } else if (endToken==null) { return token.getText(); } else { return token.getText() + endToken.getText(); } } public void setText(String text) { this.text = text; } /** * The text of the corresponding ANTLR tree node. Never null, * since the two trees are isomorphic. */ public Token getToken() { return getFirstChildToken(); } public Token getMainToken() { return token; } public Token getMainEndToken() { return endToken; } public String getLocation() { Token token = getToken(); Token endToken = getEndToken(); if (token==null) { return "unknown location"; } else if (endToken==null) { return toLocation(token); } else { return toLocation(token) + "-" + toEndLocation(endToken); } } public Integer getStartIndex() { Token token = getToken(); if (token==null) { return null; } else { CommonToken ct = (CommonToken) token; return ct.getStartIndex(); } } @Deprecated public Integer getStopIndex() { Token token = getEndToken(); if (token==null) { token = getToken(); } if (token==null) { return null; } else { CommonToken ct = (CommonToken) token; return ct.getStopIndex(); } } public Integer getEndIndex() { Token token = getEndToken(); if (token==null) { token = getToken(); } if (token==null) { return null; } else { CommonToken ct = (CommonToken) token; return ct.getStopIndex()+1; } } public Integer getDistance() { Integer start = getStartIndex(); Integer end = getEndIndex(); if (start!=null && end!=null) { return end - start; } else { return null; } } private static String toLocation(Token token) { return token.getLine() + ":" + token.getCharPositionInLine(); } private static String toEndLocation(Token token) { return token.getLine() + ":" + (token.getCharPositionInLine() + token.getText().length()-1); } private static boolean isMissingToken(Token t) { return t instanceof MissingToken; } public boolean isMissingToken() { return isMissingToken(token); } private Token getFirstChildToken() { Token token = this.token==null || //the tokens ANTLR inserts to represent missing tokens //don't come with useful offset information isMissingToken(this.token) ? null : this.token; if (firstChildToken!=null && (token==null || firstChildToken.getTokenIndex()<token.getTokenIndex())) { token = firstChildToken; } return token; } private Token getLastChildToken() { Token token=this.endToken==null || //the tokens ANTLR inserts to represent missing tokens //don't come with useful offset information isMissingToken(endToken) ? this.token : this.endToken; if (lastChildToken!=null && (token==null || lastChildToken.getTokenIndex()>token.getTokenIndex())) { token = lastChildToken; } return token; } public Token getEndToken() { return getLastChildToken(); } public void setToken(Token token) { this.token = token; } public void setEndToken(Token endToken) { //the tokens ANTLR inserts to represent missing tokens //don't come with useful offset information if (endToken==null || !isMissingToken(endToken)) { this.endToken = endToken; } } /** * The compilation errors belonging to this node. */ public List<Message> getErrors() { return errors != null ? errors : Collections.<Message>emptyList(); } public void addError(Message error){ if (errors == null) { errors = new ArrayList<Message>(2); } errors.add(error); } public void addError(String message) { addError( new AnalysisError(this, message) ); } public void addError(String message, Backend backend) { addError( new AnalysisError(this, message, backend) ); } public void addError(String message, int code) { addError( new AnalysisError(this, message, code) ); } public void addError(String message, int code, Backend backend) { addError( new AnalysisError(this, message, code, backend) ); } public void addUnexpectedError(String message) { addError( new UnexpectedError(this, message) ); } public void addUnexpectedError(String message, Backend backend) { addError( new UnexpectedError(this, message, backend) ); } public void addUnsupportedError(String message) { addError( new UnsupportedError(this, message) ); } public void addUnsupportedError(String message, Backend backend) { addError( new UnsupportedError(this, message, backend) ); } public <E extends Enum<E>> void addUsageWarning (E warningName, String message) { addError( new UsageWarning(this, message, warningName.toString()) ); } public <E extends Enum<E>> void addUsageWarning (E warningName, String message, Backend backend) { addError( new UsageWarning(this, message, warningName.toString(), backend) ); } public void addParseError(ParseError error) { addError(error); } public void addLexError(LexError error) { addError(error); } public abstract void visit(Visitor visitor); public abstract void visitChildren(Visitor visitor); @Override public String toString() { StringWriter w = new StringWriter(); PrintVisitor pv = new PrintVisitor(w); pv.visitAny(this); return w.toString(); //return getClass().getSimpleName() + "(" + text + ")"; } public String getNodeType() { return getClass().getSimpleName(); } public void handleException(Exception e, Visitor visitor) { addUnexpectedError(getMessage(e, visitor)); } public String getMessage(Exception e, Visitor visitor) { return "the '" + visitor.getClass().getSimpleName() + "' caused an exception visiting a '" + getNodeType() + "' node: '\"" + e + "\"'" + getLocationInfo(e); } private String getLocationInfo(Exception e) { return e.getStackTrace().length==0 ? "" : " at '" + e.getStackTrace()[0].toString() + "'"; } public void connect(Node child) { if (child!=null) { Token childFirstChildToken = child.getFirstChildToken(); if (childFirstChildToken!=null && (firstChildToken==null || childFirstChildToken.getTokenIndex()<firstChildToken.getTokenIndex())) { firstChildToken = childFirstChildToken; } Token childLastChildToken = child.getLastChildToken(); if (childLastChildToken!=null && (lastChildToken==null || childLastChildToken.getTokenIndex()>lastChildToken.getTokenIndex())) { lastChildToken = childLastChildToken; } } } }
package com.roboo.like.google.fragments; import java.io.DataOutputStream; import java.util.Calendar; import java.util.LinkedList; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.roboo.like.google.BusLineActivity; import com.roboo.like.google.BusStationActivity; import com.roboo.like.google.R; import com.roboo.like.google.async.BusLineAsyncTaskLoader; import com.roboo.like.google.models.BusLineItem; import com.roboo.like.google.views.BusSiteView; @SuppressLint("NewApi") public class BusLineFragment2 extends BaseWithProgressFragment implements LoaderCallbacks<LinkedList<BusLineItem>> { private static final long NEXT_QUERY_DELAY_TIME = 10000L; private static final long ONE_MINUTE_IN_MM = 60 * 1000L; public static final String ARG_BUS_LINE = "bus_line"; public static final String ARG_BUS_NAME = "bus_name"; private LinkedList<BusLineItem> mData; private HorizontalScrollView mHorizontalScrollView; private Handler mHandler = new Handler(); private Runnable mQueryRunnable = new Runnable() { @Override public void run() { doLoadData(); } }; public static BusLineFragment2 newInstance(String busLineUrl, String busName) { BusLineFragment2 fragment = new BusLineFragment2(); Bundle bundle = new Bundle(); bundle.putString(ARG_BUS_LINE, busLineUrl); bundle.putString(ARG_BUS_NAME, busName); fragment.setArguments(bundle); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = null; if (savedInstanceState == null) { view = inflater.inflate(R.layout.fragment_bus_line2, null);// TODO mHorizontalScrollView = (HorizontalScrollView) view .findViewById(R.id.hsv_scrollview); } return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); doLoadData(); } @Override public void onPause() { super.onPause(); mProgressBar.setVisibility(View.GONE); mHandler.removeCallbacks(mQueryRunnable); } @Override public void onResume() { super.onResume(); if (mData != null) { mHandler.postDelayed(mQueryRunnable, NEXT_QUERY_DELAY_TIME); } } private void setListener() {} private void doLoadData() { getActivity().getSupportLoaderManager().restartLoader(0, null, this); mProgressBar.setVisibility(View.VISIBLE); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(R.id.menu_other).setVisible(false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.activity_bus_line, menu); menu.findItem(R.id.menu_other).setVisible(false); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: onRefresh(); break; case R.id.menu_invert: invert(); break; } return super.onOptionsItemSelected(item); } private void invert() { BusLineActivity busLineActivity = (BusLineActivity) getActivity(); busLineActivity.invert(); } private void onRefresh() { mData = new LinkedList<BusLineItem>(); doLoadData(); } @Override public Loader<LinkedList<BusLineItem>> onCreateLoader(int id, Bundle args) { return new BusLineAsyncTaskLoader(getActivity(), getArguments() .getString(ARG_BUS_LINE, null)); } @Override public void onLoadFinished(Loader<LinkedList<BusLineItem>> loader, LinkedList<BusLineItem> data) { mProgressBar.setVisibility(View.GONE); mHandler.postDelayed(mQueryRunnable, NEXT_QUERY_DELAY_TIME); if (data != null) { mData = data; onGetDataSuccess(); } } private void onGetDataSuccess() { mHorizontalScrollView.removeAllViews(); int dp_48 = (int) (48 * getResources().getDisplayMetrics().density); FrameLayout frameLayout = new FrameLayout(getActivity()); FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, 5 * dp_48); frameLayoutParams.gravity = Gravity.CENTER_VERTICAL; mHorizontalScrollView.addView(frameLayout, frameLayoutParams); LinearLayout linearLayout = new LinearLayout(getActivity()); frameLayout.addView(linearLayout, new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); LayoutParams params = new LinearLayout.LayoutParams(dp_48, LayoutParams.MATCH_PARENT); for (int i = 0; i < mData.size(); i++) { final BusLineItem item = mData.get(i); final BusSiteView busItemView = new BusSiteView(getActivity()); busItemView.setPosition(i + 1); busItemView.setText(item.stationName); busItemView.setIsEnd(i == mData.size() - 1); busItemView.setIsStart(i == 0); if (!TextUtils.isEmpty(item.incomingBusNo)) { ImageView imageView = new ImageView(getActivity()); int imageViewWH = dp_48 * 2 / 3; FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( imageViewWH, imageViewWH); layoutParams.topMargin = 0; int paddingLTRB = dp_48 / 12; layoutParams.gravity = Gravity.TOP; if (isArrived(item)) { layoutParams.leftMargin = dp_48 * i + imageViewWH / 4; imageView.setImageResource(R.drawable.ic_bus_arrive); } else if (i < mData.size() - 1) { layoutParams.leftMargin = dp_48 * (1 + i) - imageViewWH / 2; imageView.setImageResource(R.drawable.ic_bus_ontheway); } frameLayout.addView(imageView, layoutParams); imageView.setPadding(paddingLTRB, paddingLTRB, paddingLTRB, paddingLTRB); imageView.setOnClickListener(new OnClickListener() { public void onClick(View v) { SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder( "" + item.stationName + "" + item.incomingBusTime); spannableStringBuilder.setSpan(new ForegroundColorSpan( 0xFFFF0000), 2, 2 + item.stationName.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); Toast.makeText(getActivity(), spannableStringBuilder, Toast.LENGTH_SHORT).show(); } }); } busItemView.getVerticalTextView().setOnClickListener( new OnClickListener() { public void onClick(View v) { getNearestCar(); busItemView.getVerticalTextView().setTextColor( 0xFFFF0000); // BusStationActivity.actionBusStation(getActivity(), item); } private void getNearestCar() { } }); busItemView.setOnClickListener( new OnClickListener() { public void onClick(View v) { BusStationActivity .actionBusStation(getActivity(), item); } }); linearLayout.addView(busItemView, params); } } private boolean isArrived(BusLineItem item) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hourOfDay = 0, minute = 0, second = 0; if (!TextUtils.isEmpty(item.incomingBusTime) && item.incomingBusTime.contains(":")) { String[] tmp = item.incomingBusTime.split(":"); hourOfDay = Integer.parseInt(tmp[0]); minute = Integer.parseInt(tmp[1]); second = Integer.parseInt(tmp[2]); } // System.out.println("year = " + year + " month = " + month + " day = " // + day); Calendar busCalendar = Calendar.getInstance(); busCalendar.set(year, month, day, hourOfDay, minute, second); // System.out.println(calendar.getTimeInMillis() + "\n" // + busCalendar.getTimeInMillis()); return calendar.getTimeInMillis() - busCalendar.getTimeInMillis() < ONE_MINUTE_IN_MM; } @Override public void onLoaderReset(Loader<LinkedList<BusLineItem>> loader) { } /*** * Root * * @param command * [chmod 777 /data/misc/wifi/wpa_supplicant.conf] * @return true false */ public static boolean runRootCommand(String command) { Process process = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { return false; } finally { try { if (os != null) { os.close(); } process.destroy(); } catch (Exception e) {} } return true; } }
package com.sensei.search.nodes; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import proj.zoie.api.IndexReaderFactory; import proj.zoie.api.ZoieIndexReader; import proj.zoie.api.ZoieIndexReader.SubReaderAccessor; import proj.zoie.api.ZoieIndexReader.SubReaderInfo; import com.browseengine.bobo.api.BoboBrowser; import com.browseengine.bobo.api.BoboIndexReader; import com.browseengine.bobo.api.BrowseException; import com.browseengine.bobo.api.BrowseHit; import com.browseengine.bobo.api.BrowseRequest; import com.browseengine.bobo.api.FacetAccessible; import com.browseengine.bobo.api.MultiBoboBrowser; import com.browseengine.bobo.sort.SortCollector; import com.google.protobuf.Message; import com.google.protobuf.TextFormat; import com.linkedin.norbert.javacompat.network.MessageHandler; import com.sensei.search.client.ResultMerger; import com.sensei.search.req.SenseiHit; import com.sensei.search.req.SenseiRequest; import com.sensei.search.req.SenseiResult; import com.sensei.search.req.protobuf.SenseiRequestBPO; import com.sensei.search.req.protobuf.SenseiRequestBPOConverter; import com.sensei.search.req.protobuf.SenseiResultBPO; import com.sensei.search.util.RequestConverter; public class SenseiNodeMessageHandler implements MessageHandler { private static final Logger logger = Logger.getLogger(SenseiNodeMessageHandler.class); private final Map<Integer,SenseiQueryBuilderFactory> _builderFactoryMap; private final Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> _partReaderMap; public SenseiNodeMessageHandler(SenseiSearchContext ctx) { _builderFactoryMap = ctx.getQueryBuilderFactoryMap(); _partReaderMap = ctx.getPartitionReaderMap(); } public int[] getPartitions(){ Set<Integer> partSet = _partReaderMap.keySet(); int[] retSet = new int[partSet.size()]; int c = 0; for (Integer part : partSet){ retSet[c++] = part; } return retSet; } public Message[] getMessages() { return new Message[] { SenseiRequestBPO.Request.getDefaultInstance() }; } private SenseiResult handleMessage(SenseiRequest senseiReq,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>> readerFactory, int partition) throws Exception{ List<ZoieIndexReader<BoboIndexReader>> readerList = null; try{ readerList = readerFactory.getIndexReaders(); if (readerList == null || readerList.size() == 0){ logger.warn("no readers were obtained from zoie, returning no hits."); return new SenseiResult(); } List<BoboIndexReader> boboReaders = ZoieIndexReader.extractDecoratedReaders(readerList); SubReaderAccessor<BoboIndexReader> subReaderAccessor = ZoieIndexReader.getSubReaderAccessor(boboReaders); MultiBoboBrowser browser = null; try { browser = new MultiBoboBrowser(BoboBrowser.createBrowsables(boboReaders)); BrowseRequest breq = RequestConverter.convert(senseiReq, _builderFactoryMap.get(partition)); SenseiResult res = browse(browser, breq, subReaderAccessor); return res; } catch(Exception e){ logger.error(e.getMessage(),e); throw e; } finally { if (browser != null) { try { browser.close(); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } } } } finally{ if (readerList!=null){ readerFactory.returnIndexReaders(readerList); } } } private SenseiResult browse(MultiBoboBrowser browser, BrowseRequest req, SubReaderAccessor<BoboIndexReader> subReaderAccessor) throws BrowseException { final SenseiResult result = new SenseiResult(); long start = System.currentTimeMillis(); int offset = req.getOffset(); int count = req.getCount(); if (offset<0 || count<0){ throw new IllegalArgumentException("both offset and count must be > 0: "+offset+"/"+count); } SortCollector collector = browser.getSortCollector(req.getSort(),req.getQuery(), offset, count, req.isFetchStoredFields(),false); Map<String, FacetAccessible> facetCollectors = new HashMap<String, FacetAccessible>(); browser.browse(req, collector, facetCollectors); BrowseHit[] hits = null; try{ hits = collector.topDocs(); } catch (IOException e){ logger.error(e.getMessage(), e); hits = new BrowseHit[0]; } SenseiHit[] senseiHits = new SenseiHit[hits.length]; for(int i = 0; i < hits.length; i++) { BrowseHit hit = hits[i]; SenseiHit senseiHit = new SenseiHit(); int docid = hit.getDocid(); SubReaderInfo<BoboIndexReader> readerInfo = subReaderAccessor.getSubReaderInfo(docid); int uid = (int)((ZoieIndexReader<BoboIndexReader>)readerInfo.subreader.getInnerReader()).getUID(readerInfo.subdocid); senseiHit.setUID(uid); senseiHit.setDocid(docid); senseiHit.setScore(hit.getScore()); senseiHit.setComparable(hit.getComparable()); senseiHit.setFieldValues(hit.getFieldValues()); senseiHit.setStoredFields(hit.getStoredFields()); senseiHit.setExplanation(hit.getExplanation()); senseiHits[i] = senseiHit; } result.setHits(senseiHits); result.setNumHits(collector.getTotalHits()); result.setTotalDocs(browser.numDocs()); result.addAll(facetCollectors); long end = System.currentTimeMillis(); result.setTime(end - start); // set the transaction ID to trace transactions result.setTid(req.getTid()); return result; } public Message handleMessage(Message msg) throws Exception { SenseiRequestBPO.Request req = (SenseiRequestBPO.Request) msg; if (logger.isDebugEnabled()){ String reqString = TextFormat.printToString(req); reqString = reqString.replace('\r', ' ').replace('\n', ' '); } SenseiRequest senseiReq = SenseiRequestBPOConverter.convert(req); SenseiResult finalResult=null; Set<Integer> partitions = senseiReq.getPartitions(); if (partitions!=null && partitions.size() > 0){ logger.info("serving partitions: "+ partitions.toString()); ArrayList<SenseiResult> resultList = new ArrayList<SenseiResult>(partitions.size()); for (int partition : partitions){ try{ long start = System.currentTimeMillis(); IndexReaderFactory<ZoieIndexReader<BoboIndexReader>> readerFactory=_partReaderMap.get(partition); SenseiResult res = handleMessage(senseiReq, readerFactory, partition); resultList.add(res); long end = System.currentTimeMillis(); logger.info("searching partition: "+partition+" took: "+(end-start)); } catch(Exception e){ logger.error(e.getMessage(),e); } } finalResult = ResultMerger.merge(senseiReq, resultList,true); } else{ logger.info("no partitions specified"); finalResult = new SenseiResult(); } return SenseiRequestBPOConverter.convert(finalResult); } }
package com.thaiopensource.datatype.xsd; import org.relaxng.datatype.ValidationContext; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; class DateTimeDatatype extends RegexDatatype implements OrderRelation { static private final String YEAR_PATTERN = "-?([1-9][0-9]*)?[0-9]{4}"; static private final String MONTH_PATTERN = "[0-9]{2}"; static private final String DAY_OF_MONTH_PATTERN = "[0-9]{2}"; static private final String TIME_PATTERN = "[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]*)?"; static private final String TZ_PATTERN = "(Z|[+\\-][0-9][0-9]:[0-5][0-9])?"; private final String template; /** * The argument specifies the lexical representation accepted: * Y specifies a year with optional preceding minus * M specifies a two digit month * D specifies a two digit day of month * t specifies a time (hh:mm:ss.sss) * any other character stands for itself. * All lexical representations are implicitly followed by an optional time zone. */ DateTimeDatatype(String template) { super(makePattern(template)); this.template = template; } static private String makePattern(String template) { StringBuffer pattern = new StringBuffer(); for (int i = 0, len = template.length(); i < len; i++) { char c = template.charAt(i); switch (c) { case 'Y': pattern.append(YEAR_PATTERN); break; case 'M': pattern.append(MONTH_PATTERN); break; case 'D': pattern.append(DAY_OF_MONTH_PATTERN); break; case 't': pattern.append(TIME_PATTERN); break; default: pattern.append(c); break; } } pattern.append(TZ_PATTERN); return pattern.toString(); } boolean allowsValue(String str, ValidationContext vc) { return getValue(str, vc) != null; } static private class DateTime { private final Date date; private final int leapMilliseconds; private final boolean hasTimeZone; DateTime(Date date, int leapMilliseconds, boolean hasTimeZone) { this.date = date; this.leapMilliseconds = leapMilliseconds; this.hasTimeZone = hasTimeZone; } public boolean equals(Object obj) { if (!(obj instanceof DateTime)) return false; DateTime other = (DateTime)obj; return (this.date.equals(other.date) && this.leapMilliseconds == other.leapMilliseconds && this.hasTimeZone == other.hasTimeZone); } public int hashCode() { return date.hashCode(); } Date getDate() { return date; } int getLeapMilliseconds() { return leapMilliseconds; } boolean getHasTimeZone() { return hasTimeZone; } } // XXX Check leap second validity? // XXX Allow 24:00:00? Object getValue(String str, ValidationContext vc) { boolean negative = false; int year = 2000; // any leap year will do int month = 1; int day = 1; int hours = 0; int minutes = 0; int seconds = 0; int milliseconds = 0; int pos = 0; int len = str.length(); for (int templateIndex = 0, templateLength = template.length(); templateIndex < templateLength; templateIndex++) { char templateChar = template.charAt(templateIndex); switch (templateChar) { case 'Y': negative = str.charAt(pos) == '-'; int yearStartIndex = negative ? pos + 1 : pos; pos = skipDigits(str, yearStartIndex); try { year = Integer.parseInt(str.substring(yearStartIndex, pos)); } catch (NumberFormatException e) { return null; } break; case 'M': month = parse2Digits(str, pos); pos += 2; break; case 'D': day = parse2Digits(str, pos); pos += 2; break; case 't': hours = parse2Digits(str, pos); pos += 3; minutes = parse2Digits(str, pos); pos += 3; seconds = parse2Digits(str, pos); pos += 2; if (pos < len && str.charAt(pos) == '.') { int end = skipDigits(str, ++pos); for (int j = 0; j < 3; j++) { milliseconds *= 10; if (pos < end) milliseconds += str.charAt(pos++) - '0'; } pos = end; } break; default: pos++; break; } } boolean hasTimeZone = pos < len; int tzOffset; if (hasTimeZone && str.charAt(pos) != 'Z') tzOffset = parseTimeZone(str, pos); else tzOffset = 0; int leapMilliseconds; if (seconds == 60) { leapMilliseconds = milliseconds + 1; milliseconds = 999; seconds = 59; } else leapMilliseconds = 0; try { GregorianCalendar cal = CalendarFactory.getCalendar(); Date date; if (cal == CalendarFactory.cal) { synchronized (cal) { date = createDate(cal, tzOffset, negative, year, month, day, hours, minutes, seconds, milliseconds); } } else date = createDate(cal, tzOffset, negative, year, month, day, hours, minutes, seconds, milliseconds); return new DateTime(date, leapMilliseconds, hasTimeZone); } catch (IllegalArgumentException e) { return null; } } // The GregorianCalendar constructor is incredibly slow with some // versions of GCJ (specifically the version shipped with RedHat 9). // This code attempts to detect when construction is slow. // When it is, we synchronize access to a single // object; otherwise, we create a new object each time we need it // so as to avoid thread lock contention. static class CalendarFactory { static private final int UNKNOWN = -1; static private final int SLOW = 0; static private final int FAST = 1; static private final int LIMIT = 10; static private int speed = UNKNOWN; static GregorianCalendar cal = new GregorianCalendar(); static GregorianCalendar getCalendar() { // Don't need to synchronize this because speed is atomic. switch (speed) { case SLOW: return cal; case FAST: return new GregorianCalendar(); } // Note that we are not timing the first construction (which happens // at class initialization), since that may involve one-time cache // initialization. long start = System.currentTimeMillis(); GregorianCalendar tem = new GregorianCalendar(); long time = System.currentTimeMillis() - start; speed = time > LIMIT ? SLOW : FAST; return tem; } } private static Date createDate(GregorianCalendar cal, int tzOffset, boolean negative, int year, int month, int day, int hours, int minutes, int seconds, int milliseconds) { cal.setLenient(false); cal.setGregorianChange(new Date(Long.MIN_VALUE)); cal.clear(); // Using a time zone of "GMT+XX:YY" doesn't work with JDK 1.1, so we have to do it like this. cal.set(Calendar.ZONE_OFFSET, tzOffset); cal.set(Calendar.DST_OFFSET, 0); cal.set(Calendar.ERA, negative ? GregorianCalendar.BC : GregorianCalendar.AD); // months in ISO8601 start with 1; months in Java start with 0 month -= 1; cal.set(year, month, day, hours, minutes, seconds); cal.set(Calendar.MILLISECOND, milliseconds); checkDate(cal.isLeapYear(year), month, day); // for GCJ return cal.getTime(); } static private void checkDate(boolean isLeapYear, int month, int day) { if (month < 0 || month > 11 || day < 1) throw new IllegalArgumentException(); int dayMax; switch (month) { // Thirty days have September, April, June and November... case Calendar.SEPTEMBER: case Calendar.APRIL: case Calendar.JUNE: case Calendar.NOVEMBER: dayMax = 30; break; case Calendar.FEBRUARY: dayMax = isLeapYear ? 29 : 28; break; default: dayMax = 31; break; } if (day > dayMax) throw new IllegalArgumentException(); } static private int parseTimeZone(String str, int i) { int sign = str.charAt(i) == '-' ? -1 : 1; return (Integer.parseInt(str.substring(i + 1, i + 3))*60 + Integer.parseInt(str.substring(i + 4)))*60*1000*sign; } static private int parse2Digits(String str, int i) { return (str.charAt(i) - '0')*10 + (str.charAt(i + 1) - '0'); } static private int skipDigits(String str, int i) { for (int len = str.length(); i < len; i++) { if ("0123456789".indexOf(str.charAt(i)) < 0) break; } return i; } OrderRelation getOrderRelation() { return this; } static private final int TIME_ZONE_MAX = 14*60*60*1000; public boolean isLessThan(Object obj1, Object obj2) { DateTime dt1 = (DateTime)obj1; DateTime dt2 = (DateTime)obj2; long t1 = dt1.getDate().getTime(); long t2 = dt2.getDate().getTime(); if (dt1.getHasTimeZone() == dt2.getHasTimeZone()) return isLessThan(t1, dt1.getLeapMilliseconds(), t2, dt2.getLeapMilliseconds()); else if (!dt2.getHasTimeZone()) return isLessThan(t1, dt1.getLeapMilliseconds(), t2 - TIME_ZONE_MAX, dt2.getLeapMilliseconds()); else return isLessThan(t1 + TIME_ZONE_MAX, dt1.getLeapMilliseconds(), t2, dt2.getLeapMilliseconds()); } static private boolean isLessThan(long t1, int leapMillis1, long t2, int leapMillis2) { if (t1 < t2) return true; if (t1 > t2) return false; if (leapMillis1 < leapMillis2) return true; return false; } }
package de.andreasgiemza.jgeagle.panels; import de.andreasgiemza.jgeagle.options.Options; import de.andreasgiemza.jgeagle.repo.rcs.JGit; import java.awt.Color; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SpinnerNumberModel; import org.eclipse.jgit.api.errors.GitAPIException; /** * * @author Andreas Giemza */ public class PreferencesPanel extends javax.swing.JPanel { private final JDialog jDialog; private final Options options; /** * Creates new form OptionsPanel * * @param jDialog * @param options */ public PreferencesPanel(JDialog jDialog, Options options) { initComponents(); this.jDialog = jDialog; this.options = options; loadOptions(); } private void loadOptions() { eagleBinaryTextField.setText(options.getPropEagleBinary()); eagleSchematicBackgroundTextField.setText(options.getPropSchematicBackground()); eagleSchematicBackgroundPanel.setBackground(Color.decode(options.getPropSchematicBackground())); eagleBoardBackgroundTextField.setText(options.getPropBoardBackground()); eagleBoardBackgroundPanel.setBackground(Color.decode(options.getPropBoardBackground())); diffImageSchematicDpiSpinner.setModel(new SpinnerNumberModel(options.getPropSchematicDpiAsInt(), 50, 600, 50)); diffImageBoardDpiSpinner.setModel(new SpinnerNumberModel(options.getPropBoardDpiAsInt(), 50, 600, 50)); diffImageUnchangedAlphaSpinner.setModel(new SpinnerNumberModel(options.getPropUnchangedAlphaAsDouble(), 0, 1, 0.01)); diffImageAddedElementTextField.setText(options.getPropAddedElementColor()); diffImageAddedElementPanel.setBackground(Color.decode(options.getPropAddedElementColor())); diffImageRemovedElementTextField.setText(options.getPropRemovedElementColor()); diffImageRemovedElementPanel.setBackground(Color.decode(options.getPropRemovedElementColor())); diffImageUndefinedTextField.setText(options.getPropUndefinedColor()); diffImageUndefinedPanel.setBackground(Color.decode(options.getPropUndefinedColor())); if (options.getPropPresetRepo() != null) { presetRepoTextField.setText(options.getPropPresetRepo()); } gitFollowCheckBox.setSelected(options.getPropFollowGitAsBoolean()); } private void close() { jDialog.dispose(); jDialog.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { eagleBinaryFileChooser = new javax.swing.JFileChooser(); repositoryFileChooser = new javax.swing.JFileChooser(); eaglePanel = new javax.swing.JPanel(); eagleBinaryLabel = new javax.swing.JLabel(); eagleBinaryTextField = new javax.swing.JTextField(); eagleBinaryButton = new javax.swing.JButton(); eagleSchematicBackgroundLabel = new javax.swing.JLabel(); eagleSchematicBackgroundTextField = new javax.swing.JTextField(); eagleSchematicBackgroundPanel = new javax.swing.JPanel(); eagleSchematicBackgroundButton = new javax.swing.JButton(); eagleBoardBackgroundLabel = new javax.swing.JLabel(); eagleBoardBackgroundTextField = new javax.swing.JTextField(); eagleBoardBackgroundPanel = new javax.swing.JPanel(); eagleBoardBackgroundButton = new javax.swing.JButton(); diffImagePanel = new javax.swing.JPanel(); diffImageSchematicDpiSpinner = new javax.swing.JSpinner(); diffImageBoardDpiLabel = new javax.swing.JLabel(); diffImageBoardDpiSpinner = new javax.swing.JSpinner(); diffImageUnchangedAlphaLabel = new javax.swing.JLabel(); diffImageUnchangedAlphaSpinner = new javax.swing.JSpinner(); diffImageAddedElementLabel = new javax.swing.JLabel(); diffImageAddedElementTextField = new javax.swing.JTextField(); diffImageAddedElementPanel = new javax.swing.JPanel(); diffImageAddedElementButton = new javax.swing.JButton(); diffImageRemovedElementLabel = new javax.swing.JLabel(); diffImageRemovedElementTextField = new javax.swing.JTextField(); diffImageRemovedElementPanel = new javax.swing.JPanel(); diffImageRemovedElementButton = new javax.swing.JButton(); diffImageUndefinedLabel = new javax.swing.JLabel(); diffImageUndefinedTextField = new javax.swing.JTextField(); diffImageUndefinedPanel = new javax.swing.JPanel(); diffImageUndefinedButton = new javax.swing.JButton(); diffImageSchematicDpiLabel = new javax.swing.JLabel(); presetRepoPanel = new javax.swing.JPanel(); presetRepoTextField = new javax.swing.JTextField(); presetRepoButton = new javax.swing.JButton(); gitPanel = new javax.swing.JPanel(); gitFollowCheckBox = new javax.swing.JCheckBox(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); eagleBinaryFileChooser.setDialogTitle("Select eagle binary ..."); repositoryFileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); eaglePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Eagle")); eagleBinaryLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); eagleBinaryLabel.setText("Binary"); eagleBinaryTextField.setEditable(false); eagleBinaryButton.setText("Select"); eagleBinaryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eagleBinaryButtonActionPerformed(evt); } }); eagleSchematicBackgroundLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); eagleSchematicBackgroundLabel.setText("Schematic background"); eagleSchematicBackgroundTextField.setEditable(false); eagleSchematicBackgroundPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout eagleSchematicBackgroundPanelLayout = new javax.swing.GroupLayout(eagleSchematicBackgroundPanel); eagleSchematicBackgroundPanel.setLayout(eagleSchematicBackgroundPanelLayout); eagleSchematicBackgroundPanelLayout.setHorizontalGroup( eagleSchematicBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); eagleSchematicBackgroundPanelLayout.setVerticalGroup( eagleSchematicBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); eagleSchematicBackgroundButton.setText("Choose"); eagleSchematicBackgroundButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eagleSchematicBackgroundButtonActionPerformed(evt); } }); eagleBoardBackgroundLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); eagleBoardBackgroundLabel.setText("Board background"); eagleBoardBackgroundTextField.setEditable(false); eagleBoardBackgroundPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout eagleBoardBackgroundPanelLayout = new javax.swing.GroupLayout(eagleBoardBackgroundPanel); eagleBoardBackgroundPanel.setLayout(eagleBoardBackgroundPanelLayout); eagleBoardBackgroundPanelLayout.setHorizontalGroup( eagleBoardBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); eagleBoardBackgroundPanelLayout.setVerticalGroup( eagleBoardBackgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); eagleBoardBackgroundButton.setText("Choose"); eagleBoardBackgroundButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eagleBoardBackgroundButtonActionPerformed(evt); } }); javax.swing.GroupLayout eaglePanelLayout = new javax.swing.GroupLayout(eaglePanel); eaglePanel.setLayout(eaglePanelLayout); eaglePanelLayout.setHorizontalGroup( eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, eaglePanelLayout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, eaglePanelLayout.createSequentialGroup() .addComponent(eagleBinaryLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(eagleBinaryTextField)) .addGroup(eaglePanelLayout.createSequentialGroup() .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(eagleBoardBackgroundLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eagleSchematicBackgroundLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(eaglePanelLayout.createSequentialGroup() .addComponent(eagleSchematicBackgroundTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(eagleSchematicBackgroundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(eaglePanelLayout.createSequentialGroup() .addComponent(eagleBoardBackgroundTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(eagleBoardBackgroundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(eagleBoardBackgroundButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eagleSchematicBackgroundButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eagleBinaryButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))) ); eaglePanelLayout.setVerticalGroup( eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(eaglePanelLayout.createSequentialGroup() .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(eagleBinaryButton) .addComponent(eagleBinaryTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eagleBinaryLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(eagleSchematicBackgroundButton) .addComponent(eagleSchematicBackgroundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(eagleSchematicBackgroundTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eagleSchematicBackgroundLabel))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(eagleBoardBackgroundButton) .addComponent(eagleBoardBackgroundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(eaglePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(eagleBoardBackgroundTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(eagleBoardBackgroundLabel)))) ); diffImagePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Diff image")); diffImageBoardDpiLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageBoardDpiLabel.setText("Board DPI"); diffImageUnchangedAlphaLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageUnchangedAlphaLabel.setText("Unchanged alpha"); diffImageAddedElementLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageAddedElementLabel.setText("Added elements"); diffImageAddedElementTextField.setEditable(false); diffImageAddedElementPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout diffImageAddedElementPanelLayout = new javax.swing.GroupLayout(diffImageAddedElementPanel); diffImageAddedElementPanel.setLayout(diffImageAddedElementPanelLayout); diffImageAddedElementPanelLayout.setHorizontalGroup( diffImageAddedElementPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageAddedElementPanelLayout.setVerticalGroup( diffImageAddedElementPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageAddedElementButton.setText("Choose"); diffImageAddedElementButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { diffImageAddedElementButtonActionPerformed(evt); } }); diffImageRemovedElementLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageRemovedElementLabel.setText("Removed elements"); diffImageRemovedElementTextField.setEditable(false); diffImageRemovedElementPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout diffImageRemovedElementPanelLayout = new javax.swing.GroupLayout(diffImageRemovedElementPanel); diffImageRemovedElementPanel.setLayout(diffImageRemovedElementPanelLayout); diffImageRemovedElementPanelLayout.setHorizontalGroup( diffImageRemovedElementPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageRemovedElementPanelLayout.setVerticalGroup( diffImageRemovedElementPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageRemovedElementButton.setText("Choose"); diffImageRemovedElementButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { diffImageRemovedElementButtonActionPerformed(evt); } }); diffImageUndefinedLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageUndefinedLabel.setText("Undefined"); diffImageUndefinedTextField.setEditable(false); diffImageUndefinedPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout diffImageUndefinedPanelLayout = new javax.swing.GroupLayout(diffImageUndefinedPanel); diffImageUndefinedPanel.setLayout(diffImageUndefinedPanelLayout); diffImageUndefinedPanelLayout.setHorizontalGroup( diffImageUndefinedPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageUndefinedPanelLayout.setVerticalGroup( diffImageUndefinedPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 18, Short.MAX_VALUE) ); diffImageUndefinedButton.setText("Choose"); diffImageUndefinedButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { diffImageUndefinedButtonActionPerformed(evt); } }); diffImageSchematicDpiLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); diffImageSchematicDpiLabel.setText("Schematic DPI"); javax.swing.GroupLayout diffImagePanelLayout = new javax.swing.GroupLayout(diffImagePanel); diffImagePanel.setLayout(diffImagePanelLayout); diffImagePanelLayout.setHorizontalGroup( diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(diffImagePanelLayout.createSequentialGroup() .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(diffImageRemovedElementLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) .addComponent(diffImageAddedElementLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffImageUnchangedAlphaLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffImageBoardDpiLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffImageUndefinedLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(4, 4, 4) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(diffImagePanelLayout.createSequentialGroup() .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(diffImageAddedElementTextField) .addComponent(diffImageRemovedElementTextField) .addComponent(diffImageUndefinedTextField, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(diffImageRemovedElementPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageAddedElementPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageUndefinedPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(diffImageAddedElementButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE) .addComponent(diffImageRemovedElementButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffImageUndefinedButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(diffImageUnchangedAlphaSpinner) .addComponent(diffImageBoardDpiSpinner, javax.swing.GroupLayout.Alignment.LEADING))) .addGroup(diffImagePanelLayout.createSequentialGroup() .addComponent(diffImageSchematicDpiLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(diffImageSchematicDpiSpinner)) ); diffImagePanelLayout.setVerticalGroup( diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(diffImagePanelLayout.createSequentialGroup() .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageSchematicDpiSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageSchematicDpiLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageBoardDpiSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageBoardDpiLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageUnchangedAlphaSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageUnchangedAlphaLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageAddedElementTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageAddedElementLabel)) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(diffImageAddedElementButton, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(diffImageAddedElementPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(diffImageRemovedElementPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(diffImageRemovedElementButton) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageRemovedElementLabel) .addComponent(diffImageRemovedElementTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(diffImageUndefinedPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(diffImageUndefinedLabel) .addComponent(diffImageUndefinedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(diffImageUndefinedButton))) ); presetRepoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Preset repository")); presetRepoTextField.setEditable(false); presetRepoButton.setText("Select"); presetRepoButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { presetRepoButtonActionPerformed(evt); } }); javax.swing.GroupLayout presetRepoPanelLayout = new javax.swing.GroupLayout(presetRepoPanel); presetRepoPanel.setLayout(presetRepoPanelLayout); presetRepoPanelLayout.setHorizontalGroup( presetRepoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, presetRepoPanelLayout.createSequentialGroup() .addComponent(presetRepoTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(presetRepoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) ); presetRepoPanelLayout.setVerticalGroup( presetRepoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(presetRepoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(presetRepoButton) .addComponent(presetRepoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); gitPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Git")); gitFollowCheckBox.setText("Continue listing the history of a file beyond renames."); javax.swing.GroupLayout gitPanelLayout = new javax.swing.GroupLayout(gitPanel); gitPanel.setLayout(gitPanelLayout); gitPanelLayout.setHorizontalGroup( gitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(gitFollowCheckBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); gitPanelLayout.setVerticalGroup( gitPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(gitFollowCheckBox) ); saveButton.setText("Save"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(eaglePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(diffImagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(gitPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(presetRepoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(eaglePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(diffImagePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(presetRepoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(gitPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancelButton) .addComponent(saveButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void eagleBinaryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eagleBinaryButtonActionPerformed int returnVal = eagleBinaryFileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File eagleBinary = eagleBinaryFileChooser.getSelectedFile(); if (eagleBinary.exists()) { eagleBinaryTextField.setText(eagleBinaryFileChooser.getSelectedFile().toString()); } else { JOptionPane.showMessageDialog(this, "Please select a valid eagle binary!", "Eagle binary doesn't exist!", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_eagleBinaryButtonActionPerformed private void diffImageAddedElementButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diffImageAddedElementButtonActionPerformed Color color = JColorChooser.showDialog(this, "Choose color for added elements ...", Color.decode(diffImageAddedElementTextField.getText())); if (color != null) { diffImageAddedElementTextField.setText("#" + Integer.toHexString(color.getRGB()).substring(2, 8)); diffImageAddedElementPanel.setBackground(color); } }//GEN-LAST:event_diffImageAddedElementButtonActionPerformed private void diffImageUndefinedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diffImageUndefinedButtonActionPerformed Color color = JColorChooser.showDialog( this, "Choose color for undedined ...", Color.decode(diffImageUndefinedTextField.getText())); if (color != null) { diffImageUndefinedTextField.setText("#" + Integer.toHexString(color.getRGB()).substring(2, 8)); diffImageUndefinedPanel.setBackground(color); } }//GEN-LAST:event_diffImageUndefinedButtonActionPerformed private void diffImageRemovedElementButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diffImageRemovedElementButtonActionPerformed Color color = JColorChooser.showDialog( this, "Choose color for removed elements ...", Color.decode(diffImageRemovedElementTextField.getText())); if (color != null) { diffImageRemovedElementTextField.setText("#" + Integer.toHexString(color.getRGB()).substring(2, 8)); diffImageRemovedElementPanel.setBackground(color); } }//GEN-LAST:event_diffImageRemovedElementButtonActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed options.save( eagleBinaryTextField.getText(), eagleSchematicBackgroundTextField.getText(), eagleBoardBackgroundTextField.getText(), diffImageSchematicDpiSpinner.getValue().toString(), diffImageBoardDpiSpinner.getValue().toString(), diffImageUnchangedAlphaSpinner.getValue().toString(), diffImageAddedElementTextField.getText(), diffImageRemovedElementTextField.getText(), diffImageUndefinedTextField.getText(), presetRepoTextField.getText(), gitFollowCheckBox.isSelected()); close(); }//GEN-LAST:event_saveButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed close(); }//GEN-LAST:event_cancelButtonActionPerformed private void eagleSchematicBackgroundButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eagleSchematicBackgroundButtonActionPerformed Color color = JColorChooser.showDialog(this, "Choose color for schematic background ...", Color.decode(eagleSchematicBackgroundTextField.getText())); if (color != null) { eagleSchematicBackgroundTextField.setText("#" + Integer.toHexString(color.getRGB()).substring(2, 8)); eagleSchematicBackgroundPanel.setBackground(color); } }//GEN-LAST:event_eagleSchematicBackgroundButtonActionPerformed private void eagleBoardBackgroundButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eagleBoardBackgroundButtonActionPerformed Color color = JColorChooser.showDialog(this, "Choose color for board background ...", Color.decode(eagleBoardBackgroundTextField.getText())); if (color != null) { eagleBoardBackgroundTextField.setText("#" + Integer.toHexString(color.getRGB()).substring(2, 8)); eagleBoardBackgroundPanel.setBackground(color); } }//GEN-LAST:event_eagleBoardBackgroundButtonActionPerformed private void presetRepoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_presetRepoButtonActionPerformed int returnVal = repositoryFileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { try { Path repoDirectory = repositoryFileChooser.getSelectedFile().toPath().resolve(".git"); if (Files.exists(repoDirectory)) { JGit jGit = new JGit(repoDirectory); } else { throw new IOException(); } } catch (IOException | GitAPIException ex) { JOptionPane.showMessageDialog(this, "Please select a valid git repository!", "Not a valid git repository!", JOptionPane.ERROR_MESSAGE); return; } presetRepoTextField.setText(repositoryFileChooser.getSelectedFile().toString()); } }//GEN-LAST:event_presetRepoButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JButton diffImageAddedElementButton; private javax.swing.JLabel diffImageAddedElementLabel; private javax.swing.JPanel diffImageAddedElementPanel; private javax.swing.JTextField diffImageAddedElementTextField; private javax.swing.JLabel diffImageBoardDpiLabel; private javax.swing.JSpinner diffImageBoardDpiSpinner; private javax.swing.JPanel diffImagePanel; private javax.swing.JButton diffImageRemovedElementButton; private javax.swing.JLabel diffImageRemovedElementLabel; private javax.swing.JPanel diffImageRemovedElementPanel; private javax.swing.JTextField diffImageRemovedElementTextField; private javax.swing.JLabel diffImageSchematicDpiLabel; private javax.swing.JSpinner diffImageSchematicDpiSpinner; private javax.swing.JLabel diffImageUnchangedAlphaLabel; private javax.swing.JSpinner diffImageUnchangedAlphaSpinner; private javax.swing.JButton diffImageUndefinedButton; private javax.swing.JLabel diffImageUndefinedLabel; private javax.swing.JPanel diffImageUndefinedPanel; private javax.swing.JTextField diffImageUndefinedTextField; private javax.swing.JButton eagleBinaryButton; private javax.swing.JFileChooser eagleBinaryFileChooser; private javax.swing.JLabel eagleBinaryLabel; private javax.swing.JTextField eagleBinaryTextField; private javax.swing.JButton eagleBoardBackgroundButton; private javax.swing.JLabel eagleBoardBackgroundLabel; private javax.swing.JPanel eagleBoardBackgroundPanel; private javax.swing.JTextField eagleBoardBackgroundTextField; private javax.swing.JPanel eaglePanel; private javax.swing.JButton eagleSchematicBackgroundButton; private javax.swing.JLabel eagleSchematicBackgroundLabel; private javax.swing.JPanel eagleSchematicBackgroundPanel; private javax.swing.JTextField eagleSchematicBackgroundTextField; private javax.swing.JCheckBox gitFollowCheckBox; private javax.swing.JPanel gitPanel; private javax.swing.JButton presetRepoButton; private javax.swing.JPanel presetRepoPanel; private javax.swing.JTextField presetRepoTextField; private javax.swing.JFileChooser repositoryFileChooser; private javax.swing.JButton saveButton; // End of variables declaration//GEN-END:variables }
package de.geeksfactory.opacclient.frontend; import java.util.List; import org.holoeverywhere.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.slidingmenu.lib.SlidingMenu; import com.slidingmenu.lib.SlidingMenu.OnOpenListener; import com.slidingmenu.lib.app.SlidingFragmentActivity; import de.geeksfactory.opacclient.OpacClient; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.storage.AccountDataSource; public abstract class OpacActivity extends SlidingFragmentActivity { protected OpacClient app; protected AlertDialog adialog; protected NavigationFragment mFrag; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getSupportActionBar().setHomeButtonEnabled(true); app = (OpacClient) getApplication(); setContentView(R.layout.empty_workaround); setBehindContentView(R.layout.menu_frame); FragmentTransaction t = this.getSupportFragmentManager() .beginTransaction(); mFrag = new NavigationFragment(); t.replace(R.id.menu_frame, mFrag); t.commit(); // Sliding Menu SlidingMenu sm = getSlidingMenu(); sm.setShadowWidthRes(R.dimen.shadow_width); sm.setShadowDrawable(R.drawable.shadow); sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); sm.setFadeDegree(0.35f); sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); sm.setOnOpenListener(new OnOpenListener() { @Override public void onOpen() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } }); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater mi = new MenuInflater(this); mi.inflate(R.menu.activity_opac, menu); return super.onCreateOptionsMenu(menu); } protected void dialog_no_user() { dialog_no_user(false); } protected void dialog_no_user(final boolean finish) { setContentView(R.layout.answer_error); ((Button) findViewById(R.id.btPrefs)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(OpacActivity.this, AccountListActivity.class); startActivity(intent); } }); ((TextView) findViewById(R.id.tvErrHead)).setText(""); ((TextView) findViewById(R.id.tvErrBody)) .setText(R.string.status_nouser); } protected void dialog_wrong_credentials(String s, final boolean finish) { setContentView(R.layout.answer_error); ((Button) findViewById(R.id.btPrefs)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(OpacActivity.this, AccountListActivity.class); startActivity(intent); } }); ((TextView) findViewById(R.id.tvErrBody)).setText(s); } public interface AccountSelectedListener { void accountSelected(Account account); } public void selectaccount() { selectaccount(null); } public class MetaAdapter extends ArrayAdapter<ContentValues> { private List<ContentValues> objects; private int spinneritem; @Override public View getDropDownView(int position, View contentView, ViewGroup viewGroup) { View view = null; if (objects.get(position) == null) { LayoutInflater layoutInflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater .inflate(R.layout.simple_spinner_dropdown_item, viewGroup, false); return view; } ContentValues item = objects.get(position); if (contentView == null) { LayoutInflater layoutInflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater .inflate(R.layout.simple_spinner_dropdown_item, viewGroup, false); } else { view = contentView; } TextView tvText = (TextView) view.findViewById(android.R.id.text1); tvText.setText(item.getAsString("value")); return view; } @Override public View getView(int position, View contentView, ViewGroup viewGroup) { View view = null; if (objects.get(position) == null) { LayoutInflater layoutInflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater.inflate(spinneritem, viewGroup, false); return view; } ContentValues item = objects.get(position); if (contentView == null) { LayoutInflater layoutInflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = layoutInflater.inflate(spinneritem, viewGroup, false); } else { view = contentView; } TextView tvText = (TextView) view.findViewById(android.R.id.text1); tvText.setText(item.getAsString("value")); return view; } public MetaAdapter(Context context, List<ContentValues> objects, int spinneritem) { super(context, R.layout.simple_spinner_item, objects); this.objects = objects; this.spinneritem = spinneritem; } } public void accountSelected() { } public void selectaccount(final AccountSelectedListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Get the layout inflater LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.account_add_liblist_dialog, null); ListView lv = (ListView) view.findViewById(R.id.lvBibs); AccountDataSource data = new AccountDataSource(this); data.open(); final List<Account> accounts = data.getAllAccounts(); data.close(); AccountListAdapter adapter = new AccountListAdapter(this, accounts); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { app.setAccount(accounts.get(position).getId()); adialog.dismiss(); onResume(); if (listener != null) { listener.accountSelected(accounts.get(position)); } } }); builder.setTitle(R.string.account_select) .setView(view) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { adialog.cancel(); } }) .setNeutralButton(R.string.accounts_edit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); Intent intent = new Intent(OpacActivity.this, AccountListActivity.class); startActivity(intent); } }); adialog = builder.create(); adialog.show(); } protected void unbindDrawables(View view) { if (view == null) return; if (view.getBackground() != null) { view.getBackground().setCallback(null); } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { unbindDrawables(((ViewGroup) view).getChildAt(i)); } if (!(view instanceof AdapterView)) { ((ViewGroup) view).removeAllViews(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggle(); return true; default: return super.onOptionsItemSelected(item); } } }
package de.gurkenlabs.litiengine.environment; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; 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.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.IUpdateable; import de.gurkenlabs.litiengine.configuration.Quality; import de.gurkenlabs.litiengine.entities.CollisionBox; import de.gurkenlabs.litiengine.entities.Creature; import de.gurkenlabs.litiengine.entities.ICollisionEntity; import de.gurkenlabs.litiengine.entities.ICombatEntity; import de.gurkenlabs.litiengine.entities.IEntity; import de.gurkenlabs.litiengine.entities.IMobileEntity; import de.gurkenlabs.litiengine.entities.Prop; import de.gurkenlabs.litiengine.entities.Trigger; import de.gurkenlabs.litiengine.entities.ai.IEntityController; import de.gurkenlabs.litiengine.environment.tilemap.IMap; import de.gurkenlabs.litiengine.environment.tilemap.IMapLoader; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.MapArea; import de.gurkenlabs.litiengine.environment.tilemap.MapProperty; import de.gurkenlabs.litiengine.environment.tilemap.MapUtilities; import de.gurkenlabs.litiengine.environment.tilemap.Spawnpoint; import de.gurkenlabs.litiengine.environment.tilemap.TmxMapLoader; import de.gurkenlabs.litiengine.graphics.AmbientLight; import de.gurkenlabs.litiengine.graphics.IRenderable; import de.gurkenlabs.litiengine.graphics.LightSource; import de.gurkenlabs.litiengine.graphics.RenderType; import de.gurkenlabs.litiengine.graphics.StaticShadow; import de.gurkenlabs.litiengine.graphics.StaticShadowLayer; import de.gurkenlabs.litiengine.graphics.StaticShadowType; import de.gurkenlabs.litiengine.graphics.animation.IAnimationController; import de.gurkenlabs.litiengine.graphics.particles.Emitter; import de.gurkenlabs.litiengine.physics.IMovementController; import de.gurkenlabs.litiengine.util.TimeUtilities; import de.gurkenlabs.litiengine.util.geom.GeometricUtilities; import de.gurkenlabs.litiengine.util.io.FileUtilities; /** * The Class MapContainerBase. */ public class Environment implements IEnvironment { private static final Logger log = Logger.getLogger(Environment.class.getName()); private static final Map<String, IMapObjectLoader> mapObjectLoaders; private final Map<Integer, ICombatEntity> combatEntities; private final Map<Integer, IMobileEntity> mobileEntities; private final Map<RenderType, Map<Integer, IEntity>> entities; private final Map<String, List<IEntity>> entitiesByTag; private final List<EnvironmentRenderListener> renderListeners; private final List<EnvironmentListener> listeners; private final List<EnvironmentEntityListener> entityListeners; private final Collection<IRenderable> groundRenderable; private final Collection<IRenderable> overlayRenderable; private final Collection<IRenderable> uiRenderable; private final Collection<CollisionBox> colliders; private final Collection<LightSource> lightSources; private final Collection<StaticShadow> staticShadows; private final Collection<Trigger> triggers; private final Collection<Prop> props; private final Collection<Emitter> emitters; private final Collection<Creature> creatures; private final Collection<Spawnpoint> spawnPoints; private final Collection<MapArea> mapAreas; private AmbientLight ambientLight; private StaticShadowLayer staticShadowLayer; private boolean loaded; private boolean initialized; private IMap map; private int localIdSequence = 0; private int mapIdSequence; static { mapObjectLoaders = new ConcurrentHashMap<>(); registerDefaultMapObjectLoaders(); } public Environment(final IMap map) { this(); this.map = map; this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap()); Game.getPhysicsEngine().setBounds(this.getMap().getBounds()); } /** * Instantiates a new map container base. * * @param mapPath * the mapPath */ public Environment(final String mapPath) { this(); final IMap loadedMap = Game.getMap(FileUtilities.getFileName(mapPath)); if (loadedMap == null) { final IMapLoader tmxLoader = new TmxMapLoader(); this.map = tmxLoader.loadMap(mapPath); } else { this.map = loadedMap; } this.mapIdSequence = MapUtilities.getMaxMapId(this.getMap()); Game.getPhysicsEngine().setBounds(new Rectangle(this.getMap().getSizeInPixels())); } private Environment() { this.entitiesByTag = new ConcurrentHashMap<>(); this.entities = new ConcurrentHashMap<>(); this.entities.put(RenderType.NONE, new ConcurrentHashMap<>()); this.entities.put(RenderType.GROUND, new ConcurrentHashMap<>()); this.entities.put(RenderType.NORMAL, new ConcurrentHashMap<>()); this.entities.put(RenderType.OVERLAY, new ConcurrentHashMap<>()); this.entities.put(RenderType.UI, new ConcurrentHashMap<>()); this.combatEntities = new ConcurrentHashMap<>(); this.mobileEntities = new ConcurrentHashMap<>(); this.lightSources = Collections.newSetFromMap(new ConcurrentHashMap<LightSource, Boolean>()); this.colliders = Collections.newSetFromMap(new ConcurrentHashMap<CollisionBox, Boolean>()); this.triggers = Collections.newSetFromMap(new ConcurrentHashMap<Trigger, Boolean>()); this.mapAreas = Collections.newSetFromMap(new ConcurrentHashMap<MapArea, Boolean>()); this.staticShadows = Collections.newSetFromMap(new ConcurrentHashMap<StaticShadow, Boolean>()); this.props = Collections.newSetFromMap(new ConcurrentHashMap<Prop, Boolean>()); this.emitters = Collections.newSetFromMap(new ConcurrentHashMap<Emitter, Boolean>()); this.creatures = Collections.newSetFromMap(new ConcurrentHashMap<Creature, Boolean>()); this.spawnPoints = Collections.newSetFromMap(new ConcurrentHashMap<Spawnpoint, Boolean>()); this.groundRenderable = Collections.newSetFromMap(new ConcurrentHashMap<IRenderable, Boolean>()); this.overlayRenderable = Collections.newSetFromMap(new ConcurrentHashMap<IRenderable, Boolean>()); this.uiRenderable = Collections.newSetFromMap(new ConcurrentHashMap<IRenderable, Boolean>()); this.renderListeners = new CopyOnWriteArrayList<>(); this.listeners = new CopyOnWriteArrayList<>(); this.entityListeners = new CopyOnWriteArrayList<>(); } @Override public void addRenderListener(EnvironmentRenderListener listener) { this.renderListeners.add(listener); } @Override public void removeRenderListener(EnvironmentRenderListener listener) { this.renderListeners.remove(listener); } @Override public void addListener(EnvironmentListener listener) { this.listeners.add(listener); } @Override public void removeListener(EnvironmentListener listener) { this.listeners.remove(listener); } @Override public void addEntityListener(EnvironmentEntityListener listener) { this.entityListeners.add(listener); } @Override public void removeEntityListener(EnvironmentEntityListener listener) { this.entityListeners.remove(listener); } @Override public void add(final IEntity entity) { if (entity == null) { return; } // set local map id if none is set for the entity if (entity.getMapId() == 0) { entity.setMapId(this.getLocalMapId()); } if (entity instanceof Emitter) { Emitter emitter = (Emitter) entity; this.getGroundRenderables().add(emitter.getGroundRenderable()); this.getOverlayRenderables().add(emitter.getOverlayRenderable()); this.emitters.add(emitter); } if (entity instanceof ICombatEntity) { this.combatEntities.put(entity.getMapId(), (ICombatEntity) entity); } if (entity instanceof IMobileEntity) { this.mobileEntities.put(entity.getMapId(), (IMobileEntity) entity); } if (entity instanceof Prop) { this.props.add((Prop) entity); } if (entity instanceof Creature) { this.creatures.add((Creature) entity); } if (entity instanceof CollisionBox) { this.colliders.add((CollisionBox) entity); } if (entity instanceof LightSource) { this.lightSources.add((LightSource) entity); } if (entity instanceof Trigger) { this.triggers.add((Trigger) entity); } if (entity instanceof Spawnpoint) { this.spawnPoints.add((Spawnpoint) entity); } if (entity instanceof StaticShadow) { this.staticShadows.add((StaticShadow) entity); } else if (entity instanceof MapArea) { this.mapAreas.add((MapArea) entity); } for (String rawTag : entity.getTags()) { if (rawTag == null) { continue; } final String tag = rawTag.trim().toLowerCase(); if (tag.isEmpty()) { continue; } if (this.getEntitiesByTag().containsKey(tag)) { this.getEntitiesByTag().get(tag).add(entity); continue; } this.getEntitiesByTag().put(tag, new CopyOnWriteArrayList<>()); this.getEntitiesByTag().get(tag).add(entity); } // if the environment has already been loaded, // we need to load the new entity manually if (this.loaded) { this.load(entity); } this.entities.get(entity.getRenderType()).put(entity.getMapId(), entity); this.fireEntityEvent(l -> l.entityAdded(entity)); } private void updateColorLayers(IEntity entity) { if (this.staticShadowLayer != null) { this.staticShadowLayer.updateSection(entity.getBoundingBox()); } if (this.ambientLight != null) { this.ambientLight.updateSection(entity.getBoundingBox()); } } @Override public void addToGround(IRenderable renderable) { this.getGroundRenderables().add(renderable); } @Override public void addToOverlay(IRenderable renderable) { this.getOverlayRenderables().add(renderable); } @Override public void addToUI(IRenderable renderable) { this.getUIRenderables().add(renderable); } @Override public void clear() { Game.getPhysicsEngine().clear(); this.dispose(this.getEntities()); this.dispose(this.getTriggers()); this.getCombatEntities().clear(); this.getMobileEntities().clear(); this.getLightSources().clear(); this.getCollisionBoxes().clear(); this.getSpawnPoints().clear(); this.getAreas().clear(); this.getTriggers().clear(); this.getEntitiesByTag().clear(); this.entities.get(RenderType.NONE).clear(); this.entities.get(RenderType.GROUND).clear(); this.entities.get(RenderType.NORMAL).clear(); this.entities.get(RenderType.OVERLAY).clear(); this.initialized = false; this.fireEvent(l -> l.environmentCleared(this)); } @Override public List<ICombatEntity> findCombatEntities(final Shape shape) { return this.findCombatEntities(shape, entity -> true); } @Override public List<ICombatEntity> findCombatEntities(final Shape shape, final Predicate<ICombatEntity> condition) { final ArrayList<ICombatEntity> foundCombatEntities = new ArrayList<>(); if (shape == null) { return foundCombatEntities; } // for rectangle we can just use the intersects method if (shape instanceof Rectangle2D) { final Rectangle2D rect = (Rectangle2D) shape; for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) { if (combatEntity.getHitBox().intersects(rect)) { foundCombatEntities.add(combatEntity); } } return foundCombatEntities; } // for other shapes, we check if the shape's bounds intersect the hitbox and // if so, we then check if the actual shape intersects the hitbox for (final ICombatEntity combatEntity : this.getCombatEntities().stream().filter(condition).collect(Collectors.toList())) { if (combatEntity.getHitBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(combatEntity.getHitBox(), shape)) { foundCombatEntities.add(combatEntity); } } return foundCombatEntities; } @Override public List<IEntity> findEntities(final Shape shape) { final ArrayList<IEntity> foundEntities = new ArrayList<>(); if (shape == null) { return foundEntities; } if (shape instanceof Rectangle2D) { final Rectangle2D rect = (Rectangle2D) shape; for (final IEntity entity : this.getEntities()) { if (entity.getBoundingBox().intersects(rect)) { foundEntities.add(entity); } } return foundEntities; } // for other shapes, we check if the shape's bounds intersect the hitbox // and // if so, we then check if the actual shape intersects the hitbox for (final IEntity entity : this.getEntities()) { if (entity.getBoundingBox().intersects(shape.getBounds()) && GeometricUtilities.shapeIntersects(entity.getBoundingBox(), shape)) { foundEntities.add(entity); } } return foundEntities; } @Override public IEntity get(final int mapId) { for (RenderType type : RenderType.values()) { IEntity entity = this.entities.get(type).get(mapId); if (entity != null) { return entity; } } return null; } @Override public <T extends IEntity> T get(Class<T> clss, int mapId) { IEntity ent = this.get(mapId); if (ent == null || !clss.isInstance(ent)) { return null; } return (T) ent; } @Override public IEntity get(final String name) { if (name == null || name.isEmpty()) { return null; } for (RenderType type : RenderType.values()) { for (final IEntity entity : this.entities.get(type).values()) { if (entity.getName() != null && entity.getName().equals(name)) { return entity; } } } return null; } @Override public <T extends IEntity> T get(Class<T> clss, String name) { IEntity ent = this.get(name); if (ent == null || !clss.isInstance(ent)) { return null; } return (T) ent; } @Override public <T extends IEntity> Collection<T> getByTag(String... tags) { return this.getByTag(null, tags); } @Override public <T extends IEntity> Collection<T> getByTag(Class<T> clss, String... tags) { List<T> foundEntities = new ArrayList<>(); for (String rawTag : tags) { String tag = rawTag.toLowerCase(); if (!this.getEntitiesByTag().containsKey(tag)) { continue; } for (IEntity ent : this.getEntitiesByTag().get(tag)) { if ((clss == null || clss.isInstance(ent)) && !foundEntities.contains((T) ent)) { foundEntities.add((T) ent); } } } return foundEntities; } @Override public AmbientLight getAmbientLight() { return this.ambientLight; } @Override public Collection<MapArea> getAreas() { return this.mapAreas; } @Override public MapArea getArea(final int mapId) { return getById(this.getAreas(), mapId); } @Override public MapArea getArea(final String name) { return getByName(this.getAreas(), name); } @Override public Collection<Emitter> getEmitters() { return this.emitters; } @Override public Emitter getEmitter(int mapId) { return getById(this.getEmitters(), mapId); } @Override public Emitter getEmitter(String name) { return getByName(this.getEmitters(), name); } @Override public Collection<CollisionBox> getCollisionBoxes() { return this.colliders; } @Override public CollisionBox getCollisionBox(int mapId) { return getById(this.getCollisionBoxes(), mapId); } @Override public CollisionBox getCollisionBox(String name) { return getByName(this.getCollisionBoxes(), name); } @Override public Collection<ICombatEntity> getCombatEntities() { return this.combatEntities.values(); } @Override public ICombatEntity getCombatEntity(final int mapId) { return getById(this.getCombatEntities(), mapId); } @Override public ICombatEntity getCombatEntity(String name) { return getByName(this.getCombatEntities(), name); } @Override public Collection<IEntity> getEntities() { final ArrayList<IEntity> ent = new ArrayList<>(); ent.addAll(this.entities.get(RenderType.NONE).values()); ent.addAll(this.entities.get(RenderType.GROUND).values()); ent.addAll(this.entities.get(RenderType.NORMAL).values()); ent.addAll(this.entities.get(RenderType.OVERLAY).values()); return ent; } @Override public Collection<IEntity> getEntities(final RenderType renderType) { return this.entities.get(renderType).values(); } public Map<String, List<IEntity>> getEntitiesByTag() { return this.entitiesByTag; } @Override public <T extends IEntity> Collection<T> getByType(Class<T> cls) { List<T> foundEntities = new ArrayList<>(); for (IEntity ent : this.getEntities()) { if (cls.isInstance(ent)) { foundEntities.add((T) ent); } } return foundEntities; } @Override public Collection<IRenderable> getGroundRenderables() { return this.groundRenderable; } @Override public Collection<IRenderable> getUIRenderables() { return this.uiRenderable; } @Override public Collection<LightSource> getLightSources() { return this.lightSources; } @Override public LightSource getLightSource(final int mapId) { return getById(this.getLightSources(), mapId); } @Override public LightSource getLightSource(String name) { return getByName(this.getLightSources(), name); } /** * Negative map ids are only used locally. */ @Override public synchronized int getLocalMapId() { return --localIdSequence; } @Override public IMap getMap() { return this.map; } @Override public Collection<IMobileEntity> getMobileEntities() { return this.mobileEntities.values(); } @Override public IMobileEntity getMobileEntity(final int mapId) { return getById(this.getMobileEntities(), mapId); } @Override public IMobileEntity getMobileEntity(String name) { return getByName(this.getMobileEntities(), name); } @Override public synchronized int getNextMapId() { return ++mapIdSequence; } @Override public Collection<IRenderable> getOverlayRenderables() { return this.overlayRenderable; } @Override public Collection<Prop> getProps() { return this.props; } @Override public Prop getProp(int mapId) { return getById(this.getProps(), mapId); } @Override public Prop getProp(String name) { return getByName(this.getProps(), name); } @Override public Creature getCreature(int mapId) { return getById(this.getCreatures(), mapId); } @Override public Creature getCreature(String name) { return getByName(this.getCreatures(), name); } @Override public Collection<Creature> getCreatures() { return this.creatures; } @Override public Spawnpoint getSpawnpoint(final int mapId) { return getById(this.getSpawnPoints(), mapId); } @Override public Spawnpoint getSpawnpoint(final String name) { return getByName(this.getSpawnPoints(), name); } @Override public Collection<Spawnpoint> getSpawnPoints() { return this.spawnPoints; } @Override public Collection<StaticShadow> getStaticShadows() { return this.staticShadows; } @Override public StaticShadow getStaticShadow(int mapId) { return getById(this.getStaticShadows(), mapId); } @Override public StaticShadow getStaticShadow(String name) { return getByName(this.getStaticShadows(), name); } @Override public StaticShadowLayer getStaticShadowLayer() { return this.staticShadowLayer; } @Override public Trigger getTrigger(final int mapId) { return getById(this.getTriggers(), mapId); } @Override public Trigger getTrigger(final String name) { return getByName(this.getTriggers(), name); } @Override public Collection<Trigger> getTriggers() { return this.triggers; } @Override public List<String> getUsedTags() { final List<String> tags = this.getEntitiesByTag().keySet().stream().collect(Collectors.toList()); Collections.sort(tags); return tags; } @Override public final void init() { if (this.initialized) { return; } this.loadMapObjects(); this.addStaticShadows(); this.addAmbientLight(); this.fireEvent(l -> l.environmentInitialized(this)); this.initialized = true; } @Override public boolean isLoaded() { return this.loaded; } @Override public void load() { this.init(); if (this.loaded) { return; } Game.getPhysicsEngine().setBounds(new Rectangle2D.Double(0, 0, this.getMap().getSizeInPixels().getWidth(), this.getMap().getSizeInPixels().getHeight())); for (final IEntity entity : this.getEntities()) { this.load(entity); } this.loaded = true; this.fireEvent(l -> l.environmentLoaded(this)); } @Override public void loadFromMap(final int mapId) { for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) { Optional<IMapObject> opt = layer.getMapObjects().stream().filter(mapObject -> mapObject.getType() != null && !mapObject.getType().isEmpty() && mapObject.getId() == mapId).findFirst(); if (opt.isPresent()) { IMapObject mapObject = opt.get(); this.addMapObject(mapObject); break; } } } public static void registerMapObjectLoader(IMapObjectLoader mapObjectLoader) { mapObjectLoaders.put(mapObjectLoader.getMapObjectType(), mapObjectLoader); } @Override public void reloadFromMap(final int mapId) { this.remove(mapId); this.loadFromMap(mapId); } @Override public void remove(final IEntity entity) { if (entity == null) { return; } if (this.entities.get(entity.getRenderType()) != null) { this.entities.get(entity.getRenderType()).entrySet().removeIf(e -> e.getValue().getMapId() == entity.getMapId()); } for (String tag : entity.getTags()) { this.getEntitiesByTag().get(tag).remove(entity); if (this.getEntitiesByTag().get(tag).isEmpty()) { this.getEntitiesByTag().remove(tag); } } if (entity instanceof Emitter) { Emitter emitter = (Emitter) entity; this.groundRenderable.remove(emitter.getGroundRenderable()); this.overlayRenderable.remove(emitter.getOverlayRenderable()); this.emitters.remove(emitter); } if (entity instanceof MapArea) { this.mapAreas.remove(entity); } if (entity instanceof Prop) { this.props.remove(entity); } if (entity instanceof Creature) { this.creatures.remove(entity); } if (entity instanceof CollisionBox) { this.colliders.remove(entity); this.staticShadows.removeIf(x -> x.getOrigin() != null && x.getOrigin().equals(entity)); } if (entity instanceof LightSource) { this.lightSources.remove(entity); this.updateColorLayers(entity); } if (entity instanceof Trigger) { this.triggers.remove(entity); } if (entity instanceof Spawnpoint) { this.spawnPoints.remove(entity); } if (entity instanceof StaticShadow) { this.staticShadows.remove(entity); this.updateColorLayers(entity); } if (entity instanceof IMobileEntity) { this.mobileEntities.values().remove(entity); } if (entity instanceof ICombatEntity) { this.combatEntities.values().remove(entity); } this.unload(entity); this.fireEntityEvent(l -> l.entityRemoved(entity)); } @Override public void remove(final int mapId) { final IEntity ent = this.get(mapId); if (ent == null) { return; } this.remove(ent); } @Override public <T extends IEntity> void remove(Collection<T> entities) { if (entities == null) { return; } for (T ent : entities) { this.remove(ent); } } @Override public void removeRenderable(final IRenderable renderable) { this.getGroundRenderables().remove(renderable); this.getOverlayRenderables().remove(renderable); this.getUIRenderables().remove(renderable); } @Override public void render(final Graphics2D g) { g.scale(Game.getCamera().getRenderScale(), Game.getCamera().getRenderScale()); long renderStart = System.nanoTime(); Game.getRenderEngine().renderMap(g, this.getMap()); this.fireRenderEvent(l -> l.mapRendered(g)); final double mapRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); for (final IRenderable rend : this.getGroundRenderables()) { rend.render(g); } this.fireRenderEvent(l -> l.groundRendered(g)); Game.getRenderEngine().renderEntities(g, this.entities.get(RenderType.GROUND).values(), false); final double groundRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); if (Game.getConfiguration().graphics().getGraphicQuality() == Quality.VERYHIGH) { Game.getRenderEngine().renderEntities(g, this.getLightSources(), false); } final double lightRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); Game.getRenderEngine().renderEntities(g, this.entities.get(RenderType.NORMAL).values()); this.fireRenderEvent(l -> l.entitiesRendered(g)); final double normalRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); if (this.getStaticShadows().stream().anyMatch(x -> x.getShadowType() != StaticShadowType.NONE)) { this.getStaticShadowLayer().render(g); } final double staticShadowRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); Game.getRenderEngine().renderLayers(g, this.getMap(), RenderType.OVERLAY); Game.getRenderEngine().renderEntities(g, this.entities.get(RenderType.OVERLAY).values(), false); for (final IRenderable rend : this.getOverlayRenderables()) { rend.render(g); } this.fireRenderEvent(l -> l.overlayRendered(g)); final double overlayRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); if (Game.getConfiguration().graphics().getGraphicQuality().ordinal() >= Quality.MEDIUM.ordinal() && this.getAmbientLight() != null && this.getAmbientLight().getAlpha() != 0) { this.getAmbientLight().render(g); } final double ambientLightRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); renderStart = System.nanoTime(); Game.getRenderEngine().renderEntities(g, this.entities.get(RenderType.UI).values(), false); for (final IRenderable rend : this.getUIRenderables()) { rend.render(g); } this.fireRenderEvent(l -> l.uiRendered(g)); final double uiRenderTime = TimeUtilities.nanoToMs(System.nanoTime() - renderStart); if (Game.getConfiguration().debug().isLogDetailedRenderTimes()) { log.log(Level.INFO, "render details:\n 1. map:{0}ms\n 2. ground:{1}ms\n 3. light:{2}ms\n 4. entities({8}):{3}ms\n 5. shadows:{4}ms\n 6. overlay({9} + {10}):{5}ms\n 7. ambientLight:{6}ms\n 8. ui:{7}ms", new Object[] { mapRenderTime, groundRenderTime, lightRenderTime, normalRenderTime, staticShadowRenderTime, overlayRenderTime, ambientLightRenderTime, uiRenderTime, this.getEntities(RenderType.NORMAL).size(), this.getEntities(RenderType.OVERLAY).size(), this.getOverlayRenderables().size(), }); } g.scale(1.0 / Game.getCamera().getRenderScale(), 1.0 / Game.getCamera().getRenderScale()); } private void fireEvent(Consumer<EnvironmentListener> cons) { for (EnvironmentListener listener : this.listeners) { cons.accept(listener); } } private void fireRenderEvent(Consumer<EnvironmentRenderListener> cons) { for (EnvironmentRenderListener listener : this.renderListeners) { cons.accept(listener); } } private void fireEntityEvent(Consumer<EnvironmentEntityListener> cons) { for (EnvironmentEntityListener listener : this.entityListeners) { cons.accept(listener); } } @Override public void unload() { if (!this.loaded) { return; } // unregister all updatable entities from the current environment for (final IEntity entity : this.getEntities()) { this.unload(entity); } this.loaded = false; this.fireEvent(l -> l.environmentUnloaded(this)); } protected void addMapObject(final IMapObject mapObject) { if (mapObjectLoaders.containsKey(mapObject.getType())) { Collection<IEntity> loadedEntities = mapObjectLoaders.get(mapObject.getType()).load(this, mapObject); for (IEntity entity : loadedEntities) { if (entity != null) { this.add(entity); } } } } private static <T extends IEntity> T getById(Collection<T> entities, int mapId) { for (final T m : entities) { if (m.getMapId() == mapId) { return m; } } return null; } private static <T extends IEntity> T getByName(Collection<T> entities, String name) { if (name == null || name.isEmpty()) { return null; } for (final T m : entities) { if (m.getName() != null && m.getName().equals(name)) { return m; } } return null; } private void addAmbientLight() { final int ambientAlpha = this.getMap().getCustomPropertyInt(MapProperty.AMBIENTALPHA); final Color ambientColor = this.getMap().getCustomPropertyColor(MapProperty.AMBIENTCOLOR, Color.WHITE); this.ambientLight = new AmbientLight(this, ambientColor, ambientAlpha); } private void addStaticShadows() { final int alpha = this.getMap().getCustomPropertyInt(MapProperty.SHADOWALPHA, StaticShadow.DEFAULT_ALPHA); final Color color = this.getMap().getCustomPropertyColor(MapProperty.SHADOWCOLOR, StaticShadow.DEFAULT_COLOR); this.staticShadowLayer = new StaticShadowLayer(this, alpha, color); } private void dispose(final Collection<? extends IEntity> entities) { for (final IEntity entity : entities) { if (entity instanceof IUpdateable) { Game.getLoop().detach((IUpdateable) entity); } Game.getEntityControllerManager().disposeControllers(entity); } } /** * Loads the specified entiy by performing the following steps: * <ol> * <li>add to physics engine</li> * <li>register entity for update</li> * <li>register animation controller for update</li> * <li>register movement controller for update</li> * <li>register AI controller for update</li> * </ol> * * @param entity */ private void load(final IEntity entity) { // 1. add to physics engine this.loadPhysicsEntity(entity); // 2. register for update or activate this.loadUpdatableOrEmitterEntity(entity); // 3. register animation controller for update final IAnimationController animation = Game.getEntityControllerManager().getAnimationController(entity); if (animation != null) { Game.getLoop().attach(animation); } // 4. register movement controller for update if (entity instanceof IMobileEntity) { final IMovementController<? extends IMobileEntity> movementController = Game.getEntityControllerManager().getMovementController((IMobileEntity) entity); if (movementController != null) { Game.getLoop().attach(movementController); } } // 5. register ai controller for update final IEntityController<? extends IEntity> controller = Game.getEntityControllerManager().getAIController(entity); if (controller != null) { Game.getLoop().attach(controller); } if (entity instanceof LightSource || entity instanceof StaticShadow) { this.updateColorLayers(entity); } } private void loadPhysicsEntity(IEntity entity) { if (entity instanceof CollisionBox) { final CollisionBox coll = (CollisionBox) entity; if (coll.isObstacle()) { Game.getPhysicsEngine().add(coll.getBoundingBox()); } else { Game.getPhysicsEngine().add(coll); } } else if (entity instanceof ICollisionEntity) { final ICollisionEntity coll = (ICollisionEntity) entity; if (coll.hasCollision()) { Game.getPhysicsEngine().add(coll); } } } private void loadUpdatableOrEmitterEntity(IEntity entity) { if (entity instanceof Emitter) { final Emitter emitter = (Emitter) entity; if (emitter.isActivateOnInit()) { emitter.activate(); } } else if (entity instanceof IUpdateable) { Game.getLoop().attach((IUpdateable) entity); } } private void loadMapObjects() { for (final IMapObjectLayer layer : this.getMap().getMapObjectLayers()) { for (final IMapObject mapObject : layer.getMapObjects()) { if (mapObject.getType() == null || mapObject.getType().isEmpty()) { continue; } this.addMapObject(mapObject); } } } private static void registerDefaultMapObjectLoaders() { registerMapObjectLoader(new PropMapObjectLoader()); registerMapObjectLoader(new CollisionBoxMapObjectLoader()); registerMapObjectLoader(new TriggerMapObjectLoader()); registerMapObjectLoader(new EmitterMapObjectLoader()); registerMapObjectLoader(new LightSourceMapObjectLoader()); registerMapObjectLoader(new SpawnpointMapObjectLoader()); registerMapObjectLoader(new MapAreaMapObjectLoader()); registerMapObjectLoader(new StaticShadowMapObjectLoader()); registerMapObjectLoader(new CreatureMapObjectLoader()); } /** * Unload the specified entity by performing the following steps: * <ol> * <li>remove entities from physics engine</li> * <li>unregister units from update</li> * <li>unregister ai controller from update</li> * <li>unregister animation controller from update</li> * <li>unregister movement controller from update</li> * </ol> * * @param entity */ private void unload(final IEntity entity) { // 1. remove from physics engine if (entity instanceof CollisionBox) { final CollisionBox coll = (CollisionBox) entity; if (coll.isObstacle()) { Game.getPhysicsEngine().remove(coll.getBoundingBox()); } else { Game.getPhysicsEngine().remove(coll); } } else if (entity instanceof ICollisionEntity) { final ICollisionEntity coll = (ICollisionEntity) entity; Game.getPhysicsEngine().remove(coll); } // 2. unregister from update if (entity instanceof IUpdateable) { Game.getLoop().detach((IUpdateable) entity); } // 3. unregister ai controller from update final IEntityController<? extends IEntity> controller = Game.getEntityControllerManager().getAIController(entity); if (controller != null) { Game.getLoop().detach(controller); } // 4. unregister animation controller from update final IAnimationController animation = Game.getEntityControllerManager().getAnimationController(entity); if (animation != null) { Game.getLoop().detach(animation); } // 5. unregister movement controller from update if (entity instanceof IMobileEntity) { final IMovementController<? extends IMobileEntity> movementController = Game.getEntityControllerManager().getMovementController((IMobileEntity) entity); if (movementController != null) { Game.getLoop().detach(movementController); } } if (entity instanceof Emitter) { Emitter em = (Emitter) entity; em.deactivate(); } } }
package mondrian.test; import mondrian.olap.*; import mondrian.olap.type.NumericType; import mondrian.olap.type.Type; import mondrian.rolap.RolapConnection; import mondrian.rolap.cache.CachePool; import mondrian.spi.UserDefinedFunction; import java.util.regex.Pattern; import java.util.List; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import junit.framework.Assert; /** * <code>BasicQueryTest</code> is a test case which tests simple queries * against the FoodMart database. * * @author jhyde * @since Feb 14, 2003 * @version $Id$ */ public class BasicQueryTest extends FoodMartTestCase { static final String EmptyResult = fold( "Axis "{}\n" + "Axis "Axis public BasicQueryTest(String name) { super(name); } private static final QueryAndResult[] sampleQueries = new QueryAndResult[] { new QueryAndResult( "select {[Measures].[Unit Sales]} on columns\n" + " from Sales", "Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Row #0: 266,773\n"), new QueryAndResult( "select\n" + " {[Measures].[Unit Sales]} on columns,\n" + " order(except([Promotion Media].[Media Type].members,{[Promotion Media].[Media Type].[No Media]}),[Measures].[Unit Sales],DESC) on rows\n" + "from Sales ", "Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Promotion Media].[All Media].[Daily Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Daily Paper]}\n" + "{[Promotion Media].[All Media].[Product Attachment]}\n" + "{[Promotion Media].[All Media].[Daily Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Cash Register Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio]}\n" + "{[Promotion Media].[All Media].[Street Handout]}\n" + "{[Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Promotion Media].[All Media].[Bulk Mail]}\n" + "{[Promotion Media].[All Media].[In-Store Coupon]}\n" + "{[Promotion Media].[All Media].[TV]}\n" + "{[Promotion Media].[All Media].[Sunday Paper, Radio, TV]}\n" + "{[Promotion Media].[All Media].[Radio]}\n" + "Row #0: 9,513\n" + "Row #1: 7,738\n" + "Row #2: 7,544\n" + "Row #3: 6,891\n" + "Row #4: 6,697\n" + "Row #5: 5,945\n" + "Row #6: 5,753\n" + "Row #7: 4,339\n" + "Row #8: 4,320\n" + "Row #9: 3,798\n" + "Row #10: 3,607\n" + "Row #11: 2,726\n" + "Row #12: 2,454\n"), new QueryAndResult( "select\n" + " { [Measures].[Units Shipped], [Measures].[Units Ordered] } on columns,\n" + " NON EMPTY [Store].[Store Name].members on rows\n" + "from Warehouse", "Axis "{}\n" + "Axis "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n"), new QueryAndResult( "with member [Measures].[Store Sales Last Period] as " + " '([Measures].[Store Sales], Time.PrevMember)',\n" + " format=' "select\n" + " {[Measures].[Store Sales Last Period]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Store Sales Last Period])} on rows\n" + "from Sales\n" + "where ([Time].[1998])", "Axis "{[Time].[1998]}\n" + "Axis "{[Measures].[Store Sales Last Period]}\n" + "Axis "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 82,248.42\n" + "Row #1: 67,609.82\n" + "Row #2: 60,469.89\n" + "Row #3: 55,207.50\n" + "Row #4: 39,774.34\n"), new QueryAndResult( "with member [Measures].[Total Store Sales] as 'Sum(YTD(),[Measures].[Store Sales])', format_string='#.00'\n" + "select\n" + " {[Measures].[Total Store Sales]} on columns,\n" + " {TopCount([Product].[Product Department].members,5, [Measures].[Total Store Sales])} on rows\n" + "from Sales\n" + "where ([Time].[1997].[Q2].[4])", "Axis "{[Time].[1997].[Q2].[4]}\n" + "Axis "{[Measures].[Total Store Sales]}\n" + "Axis "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "Row #0: 26526.67\n" + "Row #1: 21897.10\n" + "Row #2: 19980.90\n" + "Row #3: 17882.63\n" + "Row #4: 12963.23\n"), new QueryAndResult( "with member [Measures].[Store Profit Rate] as '([Measures].[Store Sales]-[Measures].[Store Cost])/[Measures].[Store Cost]', format = '#.00%'\n" + "select\n" + " {[Measures].[Store Cost],[Measures].[Store Sales],[Measures].[Store Profit Rate]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Profit Rate], BDESC) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Profit Rate]}\n" + "Axis "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "Row #0: 2,756.80\n" + "Row #0: 6,941.46\n" + "Row #0: 151.79%\n" + "Row #1: 595.97\n" + "Row #1: 1,500.11\n" + "Row #1: 151.71%\n" + "Row #2: 1,317.13\n" + "Row #2: 3,314.52\n" + "Row #2: 151.65%\n" + "Row #3: 15,370.61\n" + "Row #3: 38,670.41\n" + "Row #3: 151.59%\n" + "Row #4: 5,576.79\n" + "Row #4: 14,029.08\n" + "Row #4: 151.56%\n" + "Row #5: 12,972.99\n" + "Row #5: 32,571.86\n" + "Row #5: 151.07%\n" + "Row #6: 26,963.34\n" + "Row #6: 67,609.82\n" + "Row #6: 150.75%\n" + "Row #7: 6,564.09\n" + "Row #7: 16,455.43\n" + "Row #7: 150.69%\n" + "Row #8: 11,069.53\n" + "Row #8: 27,748.53\n" + "Row #8: 150.67%\n" + "Row #9: 22,030.66\n" + "Row #9: 55,207.50\n" + "Row #9: 150.59%\n" + "Row #10: 3,614.55\n" + "Row #10: 9,056.76\n" + "Row #10: 150.56%\n" + "Row #11: 32,831.33\n" + "Row #11: 82,248.42\n" + "Row #11: 150.52%\n" + "Row #12: 1,520.70\n" + "Row #12: 3,809.14\n" + "Row #12: 150.49%\n" + "Row #13: 10,108.87\n" + "Row #13: 25,318.93\n" + "Row #13: 150.46%\n" + "Row #14: 1,465.42\n" + "Row #14: 3,669.89\n" + "Row #14: 150.43%\n" + "Row #15: 15,894.53\n" + "Row #15: 39,774.34\n" + "Row #15: 150.24%\n" + "Row #16: 24,170.73\n" + "Row #16: 60,469.89\n" + "Row #16: 150.18%\n" + "Row #17: 4,705.91\n" + "Row #17: 11,756.07\n" + "Row #17: 149.82%\n" + "Row #18: 3,684.90\n" + "Row #18: 9,200.76\n" + "Row #18: 149.69%\n" + "Row #19: 5,827.58\n" + "Row #19: 14,550.05\n" + "Row #19: 149.68%\n" + "Row #20: 12,228.85\n" + "Row #20: 30,508.85\n" + "Row #20: 149.48%\n" + "Row #21: 2,830.92\n" + "Row #21: 7,058.60\n" + "Row #21: 149.34%\n" + "Row #22: 1,525.04\n" + "Row #22: 3,767.71\n" + "Row #22: 147.06%\n"), new QueryAndResult( "with\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] as '[Product].[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]',\n" + " format_string = '#.00%'\n" + "select\n" + " { [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order([Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC ) on rows\n" + "from Sales\n" + "where ( [Measures].[Unit Sales] )", "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n"), new QueryAndResult( "with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from Sales", "Axis "{}\n" + "Axis "{[Measures].[Store Sales]}\n" + "{[Measures].[Accumulated Sales]}\n" + "Axis "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Row #0: 45,539.69\n" + "Row #0: 45,539.69\n" + "Row #1: 44,058.79\n" + "Row #1: 89,598.48\n" + "Row #2: 50,029.87\n" + "Row #2: 139,628.35\n" + "Row #3: 42,878.25\n" + "Row #3: 182,506.60\n" + "Row #4: 44,456.29\n" + "Row #4: 226,962.89\n" + "Row #5: 45,331.73\n" + "Row #5: 272,294.62\n" + "Row #6: 50,246.88\n" + "Row #6: 322,541.50\n" + "Row #7: 46,199.04\n" + "Row #7: 368,740.54\n" + "Row #8: 43,825.97\n" + "Row #8: 412,566.51\n" + "Row #9: 42,342.27\n" + "Row #9: 454,908.78\n" + "Row #10: 53,363.71\n" + "Row #10: 508,272.49\n" + "Row #11: 56,965.64\n" + "Row #11: 565,238.13\n"), new QueryAndResult( "select {[Measures].[Promotion Sales]} on columns\n" + " from Sales", "Axis "{}\n" + "Axis "{[Measures].[Promotion Sales]}\n" + "Row #0: 151,211.21\n"), }; public void testSample0() { assertQueryReturns(sampleQueries[0].query, sampleQueries[0].result); } public void testSample1() { assertQueryReturns(sampleQueries[1].query, sampleQueries[1].result); } public void testSample2() { assertQueryReturns(sampleQueries[2].query, sampleQueries[2].result); } public void testSample3() { assertQueryReturns(sampleQueries[3].query, sampleQueries[3].result); } public void testSample4() { assertQueryReturns(sampleQueries[4].query, sampleQueries[4].result); } public void testSample5() { assertQueryReturns(sampleQueries[5].query, sampleQueries[5].result); } public void testSample6() { assertQueryReturns(sampleQueries[6].query, sampleQueries[6].result); } public void testSample7() { assertQueryReturns(sampleQueries[7].query, sampleQueries[7].result); } public void testSample8() { assertQueryReturns(sampleQueries[8].query, sampleQueries[8].result); } public void testGoodComments() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]/* trailing comment*/", EmptyResult); String[] comments = { "-- a basic comment\n", "// another basic comment\n", "/* yet another basic comment */", "-- a more complicated comment test\n", "-- to make it more intesting, -- we'll nest this comment\n", "-- also, \"we can put a string in the comment\"\n", "-- also, 'even a single quote string'\n", "---- and, the comment delimiter is looong\n", "/*\n" + " * next, how about a comment block?\n" + " * with several lines.\n" + " * also, \"we can put a string in the comment\"\n" + " * also, 'even a single quote string'\n" + " * also, -- another style comment is happy\n" + " */\n", "/* a simple /* nested */ comment */", " * a multiline /* nested */ comment\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/", " * /* really /* deeply */\n" + " * /* deeply\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/", "-- single-line comment containing /* multiline */ comment\n", "/* multi-line comment containing -- single-line comment */", }; List allCommentList = new ArrayList(); for (int i = 0; i < comments.length; i++) { String comment = comments[i]; allCommentList.add(comment); if (comment.indexOf("\n") >= 0) { allCommentList.add(comment.replaceAll("\n", "\r\n")); allCommentList.add(comment.replaceAll("\n", "\n\r")); allCommentList.add(comment.replaceAll("\n", " \n \n ")); } } allCommentList.add(""); final String[] allComments = (String[]) allCommentList.toArray(new String[allCommentList.size()]); // The last element of the array is the concatenation of all other // comments. StringBuffer buf = new StringBuffer(); for (int i = 0; i < allComments.length; i++) { buf.append(allComments[i]); } final String concatenatedComments = buf.toString(); allComments[allComments.length - 1] = concatenatedComments; // Comment at start of query. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( comment + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after SELECT. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( "SELECT" + comment + "{} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment within braces. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( "SELECT {" + comment + "} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment after axis name. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( "SELECT {} ON ROWS" + comment + ", {} ON COLUMNS FROM [Sales]", EmptyResult); } // Comment before slicer. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales] WHERE" + comment + "([Gender].[F])", fold( "Axis "{[Gender].[All Gender].[F]}\n" + "Axis "Axis } // Comment after query. for (int i = 0; i < allComments.length; i++) { String comment = allComments[i]; assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]" + comment, EmptyResult); } assertQueryReturns( "-- a comment test with carriage returns at the end of the lines\r\n" + "-- first, more than one single-line comment in a row\r\n" + "-- and, to make it more intesting, -- we'll nest this comment\r\n" + "-- also, \"we can put a string in the comment\"\r\n" + "-- also, 'even a single quote string'\r\n" + "---- and, the comment delimiter is looong\r\n" + "/*\r\n" + " * next, now about a comment block?\r\n" + " * with several lines.\r\n" + " * also, \"we can put a string in the comment\"\r\n" + " * also, 'even a single quote comment'\r\n" + " * also, -- another style comment is heppy\r\n" + " * also, // another style comment is heppy\r\n" + " */\r\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]\r", EmptyResult); assertQueryReturns( "/* a simple /* nested */ comment */\n" + " * a multiline /* nested */ comment\n" + "/*\n" + "*/\n" + " * /* multiline\n" + " * * nested comment\n" + " * */\n" + "*/\n" + " * /* really /* deeply */\n" + " * /* deeply\n" + " * * nested comment\n" + " * */\n" + " * */\n" + " * */\n" + "*/\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "-- an entire select statement commented out\n" + "-- SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "/*SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];*/\n" + "// SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales];\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); assertQueryReturns( "// now for some comments in a larger command\n" + "with // create calculate measure [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]\n" + " member [Product].[All Products].[Drink].[Percent of Alcoholic Drinks]/*the measure name*/as ' // begin the definition of the measure next\n" + " [Product].[All Products].[Drink].[Alcoholic Beverages]/[Product].[All Products].[Drink]', // divide number of alcoholic drinks by total # of drinks\n" + " format_string = '#.00%' // a custom format for our measure\n" + "select\n" + " { [Product].[All Products].[Drink].[Percent of Alcoholic Drinks] } on columns,\n" + " order([Customers].[All Customers].[USA].[WA].Children, [Product].[All Products].[Drink].[Percent of Alcoholic Drinks],BDESC ) on rows\n" + "from Sales\n" + "where ( [Measures].[Unit Sales] ) -- a comment at the end of the command", fold("Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Product].[All Products].[Drink].[Percent of Alcoholic Drinks]}\n" + "Axis "{[Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "Row #0: 44.05%\n" + "Row #1: 34.41%\n" + "Row #2: 34.20%\n" + "Row #3: 32.93%\n" + "Row #4: 31.05%\n" + "Row #5: 30.84%\n" + "Row #6: 30.69%\n" + "Row #7: 29.81%\n" + "Row #8: 28.82%\n" + "Row #9: 28.70%\n" + "Row #10: 28.37%\n" + "Row #11: 26.67%\n" + "Row #12: 26.60%\n" + "Row #13: 26.47%\n" + "Row #14: 26.42%\n" + "Row #15: 26.28%\n" + "Row #16: 25.96%\n" + "Row #17: 24.70%\n" + "Row #18: 21.89%\n" + "Row #19: 21.47%\n" + "Row #20: 17.47%\n" + "Row #21: 13.79%\n")); } public void testBadComments() { // Comments cannot appear inside identifiers. assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S]}", "Failed to parse query"); // Nested comments must be closed. assertThrows( "/* a simple /* nested * comment */\n" + "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", "Failed to parse query"); // We do NOT support \r as a line-end delimiter. (Too bad, Mac users.) assertThrows( "SELECT {} ON COLUMNS -- comment terminated by CR only\r, {} ON ROWS FROM [Sales]", "Failed to parse query"); } /** * Tests that a query whose axes are empty works. * (Bug 1220787.) */ public void testBothAxesEmpty() { assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS FROM [Sales]", EmptyResult); // expression which evaluates to empty set assertQueryReturns( "SELECT Filter({[Gender].MEMBERS}, 1 = 0) ON COLUMNS, \n" + "{} ON ROWS\n" + "FROM [Sales]", EmptyResult); // with slicer assertQueryReturns( "SELECT {} ON ROWS, {} ON COLUMNS \n" + "FROM [Sales] WHERE ([Gender].[F])", fold("Axis "{[Gender].[All Gender].[F]}\n" + "Axis "Axis } /** * Tests that a slicer with multiple values gives an error. * (Bug 828411.) */ public void testCompoundSlicerFails() { // two tuples assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {([Marital Status].[S]),\n" + " ([Marital Status].[M])}", "WHERE clause expression returned set with more than one element."); // set with incompatible members assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // expression which evaluates to a set with zero members is not ok assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, 1 = 0)", "WHERE clause expression returned NULL or empty set."); // expression which evaluates to a not-null member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE ( {Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)}.Item(0) )", fold("Axis "{[Marital Status].[All Marital Status]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n")); // expression which evaluates to a null member is not ok assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE [Marital Status].Parent", "WHERE clause expression returned NULL or empty set."); // expression which evaluates to a set with one member is ok assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] = 266773)", fold("Axis "{[Marital Status].[All Marital Status]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #1: 131,558\n" + "Row #2: 135,215\n")); // expression which evaluates to three tuples is not ok assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE Filter({[Marital Status].MEMBERS}, [Measures].[Unit Sales] <= 266773)", "WHERE clause expression returned set with more than one element."); // set with incompatible members assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]\n" + "WHERE {[Marital Status].[S],\n" + " [Product]}", "All arguments to function '{}' must have same hierarchy."); // two members of same dimension in columns and rows assertThrows( "SELECT CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " {[Gender].[M]}) ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]", "Dimension '[Gender]' appears in more than one independent axis."); // two members of same dimension in rows and slicer assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Gender].[F])", "Dimension '[Gender]' appears in more than one independent axis."); // two members of same dimension in slicer tuple assertThrows( "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " {[Gender].MEMBERS} ON ROWS\n" + "FROM [Sales]" + "WHERE ([Marital Status].[S], [Marital Status].[M])", "Tuple contains more than one member of dimension '[Marital Status]'."); // testcase for bug 996088 assertThrows( "select\n" + "{[Measures].[Unit Sales]} on columns,\n" + "{([Product].[All Products], [Time].[1997])} ON rows\n" + "from Sales\n" + "where ([Time].[1997])", "Dimension '[Time]' appears in more than one independent axis."); } /** * Requires the use of a sparse segment, because the product dimension * has 6 atttributes, the product of whose cardinalities is ~8M. If we * use a dense segment, we run out of memory trying to allocate a huge * array. */ public void testBigQuery() { Result result = executeQuery("SELECT {[Measures].[Unit Sales]} on columns,\n" + " {[Product].members} on rows\n" + "from Sales"); final int rowCount = result.getAxes()[1].positions.length; assertEquals(2256, rowCount); assertEquals("152", result.getCell(new int[] {0, rowCount - 1}).getFormattedValue()); } public void testNonEmpty1() { assertSize( "select\n" + " NON EMPTY CrossJoin({[Product].[All Products].[Drink].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 8, 2); } public void testNonEmpty2() { assertSize( "select\n" + " NON EMPTY CrossJoin(\n" + " {[Product].[All Products].Children},\n" + " {[Customers].[All Customers].[USA].[WA].[Bellingham]}) on rows,\n" + " NON EMPTY CrossJoin(\n" + " {[Measures].[Unit Sales]},\n" + " { [Promotion Media].[All Media].[Cash Register Handout],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", 2, 2); } public void testOneDimensionalQueryWithCompoundSlicer() { Result result = executeQuery("select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])"); assertTrue(result.getAxes().length == 1); assertTrue(result.getAxes()[0].positions.length == 3); assertTrue(result.getSlicerAxis().positions.length == 1); assertTrue(result.getSlicerAxis().positions[0].members.length == 3); } public void testSlicerIsEvaluatedBeforeAxes() { // about 10 products exceeded 20000 units in 1997, only 2 for Q1 assertSize( "SELECT {[Measures].[Unit Sales]} on columns,\n" + " filter({[Product].members}, [Measures].[Unit Sales] > 20000) on rows\n" + "FROM Sales\n" + "WHERE [Time].[1997].[Q1]", 1, 2); } public void testSlicerWithCalculatedMembers() { assertSize( "WITH MEMBER [Time].[1997].[H1] as ' Aggregate({[Time].[1997].[Q1], [Time].[1997].[Q2]})' \n" + " MEMBER [Measures].[Store Margin] as '[Measures].[Store Sales] - [Measures].[Store Cost]'\n" + "SELECT {[Gender].children} on columns,\n" + " filter({[Product].members}, [Gender].[F] > 10000) on rows\n" + "FROM Sales\n" + "WHERE ([Time].[1997].[H1], [Measures].[Store Margin])", 2, 6); } public void _testEver() { assertQueryReturns( "select\n" + " {[Measures].[Unit Sales], [Measures].[Ever]} on columns,\n" + " [Gender].members on rows\n" + "from Sales", "xxx"); } public void _testDairy() { assertQueryReturns( "with\n" + " member [Product].[Non dairy] as '[Product].[All Products] - [Product].[Food].[Dairy]'\n" + " member [Measures].[Dairy ever] as 'sum([Time].members, ([Measures].[Unit Sales],[Product].[Food].[Dairy]))'\n" + " set [Customers who never bought dairy] as 'filter([Customers].members, [Measures].[Dairy ever] = 0)'\n" + "select\n" + " {[Measures].[Unit Sales], [Measures].[Dairy ever]} on columns,\n" + " [Customers who never bought dairy] on rows\n" + "from Sales", "xxx"); } public void testSolveOrder() { assertQueryReturns( "WITH\n" + " MEMBER [Measures].[StoreType] AS \n" + " '[Store].CurrentMember.Properties(\"Store Type\")',\n" + " SOLVE_ORDER = 2\n" + " MEMBER [Measures].[ProfitPct] AS \n" + " '(Measures.[Store Sales] - Measures.[Store Cost]) / Measures.[Store Sales]',\n" + " SOLVE_ORDER = 1, FORMAT_STRING = '##.00%'\n" + "SELECT\n" + " { Descendants([Store].[USA], [Store].[Store Name])} ON COLUMNS,\n" + " { [Measures].[Store Sales], [Measures].[Store Cost], [Measures].[StoreType],\n" + " [Measures].[ProfitPct] } ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Axis "{[Measures].[Store Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[StoreType]}\n" + "{[Measures].[ProfitPct]}\n" + "Row #0: \n" + "Row #0: 45,750.24\n" + "Row #0: 54,545.28\n" + "Row #0: 54,431.14\n" + "Row #0: 4,441.18\n" + "Row #0: 55,058.79\n" + "Row #0: 87,218.28\n" + "Row #0: 4,739.23\n" + "Row #0: 52,896.30\n" + "Row #0: 52,644.07\n" + "Row #0: 49,634.46\n" + "Row #0: 74,843.96\n" + "Row #0: 4,705.97\n" + "Row #0: 24,329.23\n" + "Row #1: \n" + "Row #1: 18,266.44\n" + "Row #1: 21,771.54\n" + "Row #1: 21,713.53\n" + "Row #1: 1,778.92\n" + "Row #1: 21,948.94\n" + "Row #1: 34,823.56\n" + "Row #1: 1,896.62\n" + "Row #1: 21,121.96\n" + "Row #1: 20,956.80\n" + "Row #1: 19,795.49\n" + "Row #1: 29,959.28\n" + "Row #1: 1,880.34\n" + "Row #1: 9,713.81\n" + "Row #2: HeadQuarters\n" + "Row #2: Gourmet Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Supermarket\n" + "Row #2: Deluxe Supermarket\n" + "Row #2: Small Grocery\n" + "Row #2: Mid-Size Grocery\n" + "Row #3: \n" + "Row #3: 60.07%\n" + "Row #3: 60.09%\n" + "Row #3: 60.11%\n" + "Row #3: 59.94%\n" + "Row #3: 60.14%\n" + "Row #3: 60.07%\n" + "Row #3: 59.98%\n" + "Row #3: 60.07%\n" + "Row #3: 60.19%\n" + "Row #3: 60.12%\n" + "Row #3: 59.97%\n" + "Row #3: 60.04%\n" + "Row #3: 60.07%\n")); } public void testSolveOrderNonMeasure() { assertQueryReturns( "WITH\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + " MEMBER [Measures].[MeasuresCalc] as '2', SOLVE_ORDER=2\n" + " MEMBER [Time].[TimeCalc] as '3', SOLVE_ORDER=3\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " {( [Time].[TimeCalc], [Measures].[MeasuresCalc] )} ON rows\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Product].[ProdCalc]}\n" + "Axis "{[Time].[TimeCalc], [Measures].[MeasuresCalc]}\n" + "Row #0: 3\n")); } public void testSolveOrderNonMeasure2() { assertQueryReturns( "WITH\n" + " MEMBER [Store].[StoreCalc] as '0', SOLVE_ORDER=0\n" + " MEMBER [Product].[ProdCalc] as '1', SOLVE_ORDER=1\n" + "SELECT\n" + " { [Product].[ProdCalc] } ON columns,\n" + " { [Store].[StoreCalc] } ON rows\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Product].[ProdCalc]}\n" + "Axis "{[Store].[StoreCalc]}\n" + "Row #0: 1\n")); } public void testSolveOrderAmbiguous1() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Customers].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Customers].[Calc] } ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Promotions].[Calc]}\n" + "Axis "{[Customers].[Calc]}\n" + "Row #0: 1\n")); } /** * In the second test, the answer should be 2 because Product comes before * Promotions in the FoodMart.xml schema. */ public void testSolveOrderAmbiguous2() { assertQueryReturns( "WITH\n" + " MEMBER [Promotions].[Calc] AS '1'\n" + " MEMBER [Product].[Calc] AS '2'\n" + "SELECT\n" + " { [Promotions].[Calc] } ON COLUMNS,\n" + " { [Product].[Calc] } ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Promotions].[Calc]}\n" + "Axis "{[Product].[Calc]}\n" + "Row #0: 2\n")); } public void testCalculatedMemberWhichIsNotAMeasure() { String query = "WITH MEMBER [Product].[BigSeller] AS\n" + " 'IIf([Product].[Drink].[Alcoholic Beverages].[Beer and Wine] > 100, \"Yes\",\"No\")'\n" + "SELECT {[Product].[BigSeller],[Product].children} ON COLUMNS,\n" + " {[Store].[All Stores].[USA].[CA].children} ON ROWS\n" + "FROM Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis "{[Product].[BigSeller]}\n" + "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Axis "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: No\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #1: Yes\n" + "Row #1: 1,945\n" + "Row #1: 15,438\n" + "Row #1: 3,950\n" + "Row #2: Yes\n" + "Row #2: 2,422\n" + "Row #2: 18,294\n" + "Row #2: 4,947\n" + "Row #3: Yes\n" + "Row #3: 2,560\n" + "Row #3: 18,369\n" + "Row #3: 4,706\n" + "Row #4: No\n" + "Row #4: 175\n" + "Row #4: 1,555\n" + "Row #4: 387\n"); assertQueryReturns(query, desiredResult); } public void testMultipleCalculatedMembersWhichAreNotMeasures() { String query = "WITH\n" + " MEMBER [Store].[x] AS '1'\n" + " MEMBER [Product].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis "{[Store].[x]}\n" + "Row #0: 1\n"); assertQueryReturns(query, desiredResult); } /** * There used to be something wrong with non-measure calculated members * where the ordering of the WITH MEMBER would determine whether or not * the member would be found in the cube. This test would fail but the * previous one would work ok. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures2() { String query = "WITH\n" + " MEMBER [Product].[x] AS '1'\n" + " MEMBER [Store].[x] AS '1'\n" + "SELECT {[Store].[x]} ON COLUMNS\n" + "FROM Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis "{[Store].[x]}\n" + "Row #0: 1\n"); assertQueryReturns(query, desiredResult); } /** * This one had the same problem. It wouldn't find the * [Store].[All Stores].[x] member because it has the same leaf * name as [Product].[All Products].[x]. (see sf#1084651) */ public void testMultipleCalculatedMembersWhichAreNotMeasures3() { String query = "WITH\n" + " MEMBER [Product].[All Products].[x] AS '1'\n" + " MEMBER [Store].[All Stores].[x] AS '1'\n" + "SELECT {[Store].[All Stores].[x]} ON COLUMNS\n" + "FROM Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis "{[Store].[All Stores].[x]}\n" + "Row #0: 1\n"); assertQueryReturns(query, desiredResult); } public void testConstantString() { String s = executeExpr(" \"a string\" "); assertEquals("a string", s); } public void testConstantNumber() { String s = executeExpr(" 1234 "); assertEquals("1,234", s); } public void testCyclicalCalculatedMembers() { Util.discard(executeQuery("WITH\n" + " MEMBER [Product].[X] AS '[Product].[Y]'\n" + " MEMBER [Product].[Y] AS '[Product].[X]'\n" + "SELECT\n" + " {[Product].[X]} ON COLUMNS,\n" + " {Store.[Store Name].Members} ON ROWS\n" + "FROM Sales")); } /** * Disabled test. It used throw an 'infinite loop' error (which is what * Plato does). But now we revert to the context of the default member when * calculating calculated members (we used to stay in the context of the * calculated member), and we get a result. */ public void testCycle() { if (false) { assertExprThrows("[Time].[1997].[Q4]", "infinite loop"); } else { String s = executeExpr("[Time].[1997].[Q4]"); assertEquals("72,024", s); } } public void testHalfYears() { Util.discard(executeQuery("WITH MEMBER [Measures].[ProfitPercent] AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE ([Measures].[ProfitPercent])")); } public void _testHalfYearsTrickyCase() { Util.discard(executeQuery("WITH MEMBER MEASURES.ProfitPercent AS\n" + " '([Measures].[Store Sales]-[Measures].[Store Cost])/([Measures].[Store Cost])',\n" + " FORMAT_STRING = '#.00%', SOLVE_ORDER = 1\n" + " MEMBER [Time].[First Half 97] AS '[Time].[1997].[Q1] + [Time].[1997].[Q2]'\n" + " MEMBER [Time].[Second Half 97] AS '[Time].[1997].[Q3] + [Time].[1997].[Q4]'\n" + " SELECT {[Time].[First Half 97],\n" + " [Time].[Second Half 97],\n" + " [Time].[1997].CHILDREN} ON COLUMNS,\n" + " {[Store].[Store Country].[USA].CHILDREN} ON ROWS\n" + " FROM [Sales]\n" + " WHERE (MEASURES.ProfitPercent)")); } public void testAsSample7ButUsingVirtualCube() { Util.discard(executeQuery("with member [Measures].[Accumulated Sales] as 'Sum(YTD(),[Measures].[Store Sales])'\n" + "select\n" + " {[Measures].[Store Sales],[Measures].[Accumulated Sales]} on columns,\n" + " {Descendants([Time].[1997],[Time].[Month])} on rows\n" + "from [Warehouse and Sales]")); } public void testVirtualCube() { assertQueryReturns( // Note that Unit Sales is independent of Warehouse. "select CrossJoin(\n" + " {[Warehouse].DefaultMember, [Warehouse].[USA].children},\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales], [Measures].[Units Shipped]}) on columns,\n" + " [Time].children on rows\n" + "from [Warehouse and Sales]", fold("Axis "{}\n" + "Axis "{[Warehouse].[All Warehouses], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[CA], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[OR], [Measures].[Units Shipped]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Unit Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Store Sales]}\n" + "{[Warehouse].[All Warehouses].[USA].[WA], [Measures].[Units Shipped]}\n" + "Axis "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 66,291\n" + "Row #0: 139,628.35\n" + "Row #0: 50951.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 8539.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 7994.0\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 34418.0\n" + "Row #1: 62,610\n" + "Row #1: 132,666.27\n" + "Row #1: 49187.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 15726.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 7575.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 25886.0\n" + "Row #2: 65,848\n" + "Row #2: 140,271.89\n" + "Row #2: 57789.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 20821.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 8673.0\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 28295.0\n" + "Row #3: 72,024\n" + "Row #3: 152,671.62\n" + "Row #3: 49799.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 15791.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 16666.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 17342.0\n")); } public void testUseDimensionAsShorthandForMember() { Util.discard(executeQuery("select {[Measures].[Unit Sales]} on columns,\n" + " {[Store], [Store].children} on rows\n" + "from [Sales]")); } public void _testMembersFunction() { Util.discard(executeQuery("select {[Measures].[Unit Sales]} on columns,\n" + " {[Customers].members(0)} on rows\n" + "from [Sales]")); } public void _testProduct2() { final Axis axis = getTestContext().executeAxis("{[Product2].members}"); System.out.println(TestContext.toString(axis.positions)); } public static final QueryAndResult[] taglibQueries = { new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} on columns,\n" + " CrossJoin(\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] },\n" + " [Product].[All Products].[Drink].children) on rows\n" + "from Sales\n" + "where ([Time].[1997])", "Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n"), new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75\n" + "Row #0: 76\n" + "Row #0: 148\n" + "Row #0: 158\n" + "Row #0: 168.62\n" + "Row #0: 182.38\n" + "Row #0: 316.88\n" + "Row #0: 294.55\n" + "Row #1: 97\n" + "Row #1: 188\n" + "Row #1: 197\n" + "Row #1: 270\n" + "Row #1: 186.03\n" + "Row #1: 419.14\n" + "Row #1: 399.58\n" + "Row #1: 520.55\n" + "Row #2: 54\n" + "Row #2: 68\n" + "Row #2: 85\n" + "Row #2: 84\n" + "Row #2: 89.03\n" + "Row #2: 119.55\n" + "Row #2: 140.27\n" + "Row #2: 128.32\n"), new QueryAndResult( "select\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns,\n" + " Order([Product].[Product Department].members, [Measures].[Store Sales], DESC) on rows\n" + "from Sales", "Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Sales]}\n" + "Axis "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "{[Product].[All Products].[Food].[Canned Foods]}\n" + "{[Product].[All Products].[Food].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Dairy]}\n" + "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Baked Goods]}\n" + "{[Product].[All Products].[Food].[Snacks]}\n" + "{[Product].[All Products].[Food].[Starchy Foods]}\n" + "{[Product].[All Products].[Food].[Eggs]}\n" + "{[Product].[All Products].[Food].[Breakfast Foods]}\n" + "{[Product].[All Products].[Food].[Seafood]}\n" + "{[Product].[All Products].[Food].[Meat]}\n" + "{[Product].[All Products].[Food].[Canned Products]}\n" + "{[Product].[All Products].[Non-Consumable].[Household]}\n" + "{[Product].[All Products].[Non-Consumable].[Health and Hygiene]}\n" + "{[Product].[All Products].[Non-Consumable].[Periodicals]}\n" + "{[Product].[All Products].[Non-Consumable].[Checkout]}\n" + "{[Product].[All Products].[Non-Consumable].[Carousel]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 37,792\n" + "Row #0: 82,248.42\n" + "Row #1: 30,545\n" + "Row #1: 67,609.82\n" + "Row #2: 26,655\n" + "Row #2: 55,207.50\n" + "Row #3: 19,026\n" + "Row #3: 39,774.34\n" + "Row #4: 20,245\n" + "Row #4: 38,670.41\n" + "Row #5: 12,885\n" + "Row #5: 30,508.85\n" + "Row #6: 12,037\n" + "Row #6: 25,318.93\n" + "Row #7: 7,870\n" + "Row #7: 16,455.43\n" + "Row #8: 6,884\n" + "Row #8: 14,550.05\n" + "Row #9: 5,262\n" + "Row #9: 11,756.07\n" + "Row #10: 4,132\n" + "Row #10: 9,200.76\n" + "Row #11: 3,317\n" + "Row #11: 6,941.46\n" + "Row #12: 1,764\n" + "Row #12: 3,809.14\n" + "Row #13: 1,714\n" + "Row #13: 3,669.89\n" + "Row #14: 1,812\n" + "Row #14: 3,314.52\n" + "Row #15: 27,038\n" + "Row #15: 60,469.89\n" + "Row #16: 16,284\n" + "Row #16: 32,571.86\n" + "Row #17: 4,294\n" + "Row #17: 9,056.76\n" + "Row #18: 1,779\n" + "Row #18: 3,767.71\n" + "Row #19: 841\n" + "Row #19: 1,500.11\n" + "Row #20: 13,573\n" + "Row #20: 27,748.53\n" + "Row #21: 6,838\n" + "Row #21: 14,029.08\n" + "Row #22: 4,186\n" + "Row #22: 7,058.60\n"), new QueryAndResult( "select\n" + " [Product].[All Products].[Drink].children on columns\n" + "from Sales\n" + "where ([Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997])", "Axis "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout], [Time].[1997]}\n" + "Axis "{[Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[All Products].[Drink].[Beverages]}\n" + "{[Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 158\n" + "Row #0: 270\n" + "Row #0: 84\n"), new QueryAndResult( "select\n" + " NON EMPTY CrossJoin([Product].[All Products].[Drink].children, [Customers].[All Customers].[USA].[WA].Children) on rows,\n" + " CrossJoin(\n" + " {[Measures].[Unit Sales], [Measures].[Store Sales]},\n" + " { [Promotion Media].[All Media].[Radio],\n" + " [Promotion Media].[All Media].[TV],\n" + " [Promotion Media].[All Media].[Sunday Paper],\n" + " [Promotion Media].[All Media].[Street Handout] }\n" + " ) on columns\n" + "from Sales\n" + "where ([Time].[1997])", "Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Unit Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Radio]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[TV]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Sunday Paper]}\n" + "{[Measures].[Store Sales], [Promotion Media].[All Media].[Street Handout]}\n" + "Axis "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Anacortes]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Edmonds]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Sedro Woolley]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Walla Walla]}\n" + "{[Product].[All Products].[Drink].[Beverages], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Ballard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bellingham]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Bremerton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Burien]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Everett]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Issaquah]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Kirkland]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Lynnwood]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Marysville]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Olympia]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Port Orchard]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Puyallup]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Redmond]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Renton]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Seattle]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Spokane]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Tacoma]}\n" + "{[Product].[All Products].[Drink].[Dairy], [Customers].[All Customers].[USA].[WA].[Yakima]}\n" + "Row #0: \n" + "Row #0: 2\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 1.14\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 4\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 4\n" + "Row #1: 10.40\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 2.16\n" + "Row #2: \n" + "Row #2: 1\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 2.37\n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 24\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 46.09\n" + "Row #3: \n" + "Row #4: 3\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 8\n" + "Row #4: 2.10\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 9.63\n" + "Row #5: 6\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 5\n" + "Row #5: 8.06\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: 6.21\n" + "Row #6: 3\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 7\n" + "Row #6: 7.80\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: 15.00\n" + "Row #7: 14\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #7: 36.10\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #8: 3\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 16\n" + "Row #8: 10.29\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: 32.20\n" + "Row #9: 3\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #9: 10.56\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 15\n" + "Row #10: 11\n" + "Row #10: \n" + "Row #10: \n" + "Row #10: 34.79\n" + "Row #10: 15.67\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 7\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 17.44\n" + "Row #11: \n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 22\n" + "Row #12: 9\n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 32.35\n" + "Row #12: 17.43\n" + "Row #13: 7\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 4\n" + "Row #13: 4.77\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: 15.16\n" + "Row #14: 4\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 4\n" + "Row #14: 3.64\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 9.64\n" + "Row #15: 2\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 7\n" + "Row #15: 6.86\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 8.38\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 28\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 61.98\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 3\n" + "Row #17: 4\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: 10.56\n" + "Row #17: 8.96\n" + "Row #18: 6\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 3\n" + "Row #18: 7.16\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 8.10\n" + "Row #19: 7\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #19: 15.63\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: \n" + "Row #20: 3\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 13\n" + "Row #20: 6.96\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 12.22\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 16\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 45.08\n" + "Row #21: \n" + "Row #22: 3\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 18\n" + "Row #22: 6.39\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: 21.08\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 21\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 33.22\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 9\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 22.65\n" + "Row #25: 2\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 9\n" + "Row #25: 6.80\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 18.90\n" + "Row #26: 3\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 9\n" + "Row #26: 1.50\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: 23.01\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 22\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: 50.71\n" + "Row #28: 4\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #28: 5.16\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 20\n" + "Row #29: 14\n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 48.02\n" + "Row #29: 28.80\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 14\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 19.96\n" + "Row #30: \n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 10\n" + "Row #31: 40\n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 26.36\n" + "Row #31: 74.49\n" + "Row #32: 6\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #32: 17.01\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: \n" + "Row #33: 4\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #33: 2.80\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #34: 4\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #34: 7.98\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 46\n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: 81.71\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 21\n" + "Row #36: 6\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 37.93\n" + "Row #36: 14.73\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 3\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 7.92\n" + "Row #37: \n" + "Row #38: 25\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 3\n" + "Row #38: 51.65\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 2.34\n" + "Row #39: 3\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 4\n" + "Row #39: 4.47\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: 9.20\n" + "Row #40: \n" + "Row #40: 1\n" + "Row #40: \n" + "Row #40: \n" + "Row #40: \n" + "Row #40: 1.47\n" + "Row #40: \n" + "Row #40: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 15\n" + "Row #41: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 18.88\n" + "Row #41: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3\n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 3.75\n" + "Row #43: 9\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 10\n" + "Row #43: 31.41\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: 15.12\n" + "Row #44: 3\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 3\n" + "Row #44: 7.41\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 2.55\n" + "Row #45: 3\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #45: 1.71\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 7\n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 11.86\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 3\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 2.76\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4\n" + "Row #48: 5\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4.50\n" + "Row #48: 7.27\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 7\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 10.01\n" + "Row #49: \n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 5\n" + "Row #50: 4\n" + "Row #50: \n" + "Row #50: \n" + "Row #50: 12.88\n" + "Row #50: 5.28\n" + "Row #51: 2\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #51: 2.64\n" + "Row #51: \n" + "Row #51: \n" + "Row #51: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 5\n" + "Row #52: \n" + "Row #52: \n" + "Row #52: \n" + "Row #52: 12.34\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 5\n" + "Row #53: \n" + "Row #53: \n" + "Row #53: \n" + "Row #53: 3.41\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 4\n" + "Row #54: \n" + "Row #54: \n" + "Row #54: \n" + "Row #54: 2.44\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 2\n" + "Row #55: \n" + "Row #55: \n" + "Row #55: \n" + "Row #55: 6.92\n" + "Row #55: \n" + "Row #56: 13\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7\n" + "Row #56: 23.69\n" + "Row #56: \n" + "Row #56: \n" + "Row #56: 7.07\n"), new QueryAndResult( "select from Sales\n" + "where ([Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV])", "Axis "{[Measures].[Store Sales], [Time].[1997], [Promotion Media].[All Media].[TV]}\n" + "7,786.21"), }; public void testTaglib0() { assertQueryReturns(taglibQueries[0].query, taglibQueries[0].result); } public void testTaglib1() { assertQueryReturns(taglibQueries[1].query, taglibQueries[1].result); } public void testTaglib2() { assertQueryReturns(taglibQueries[2].query, taglibQueries[2].result); } public void testTaglib3() { assertQueryReturns(taglibQueries[3].query, taglibQueries[3].result); } public void testTaglib4() { assertQueryReturns(taglibQueries[4].query, taglibQueries[4].result); } public void testTaglib5() { assertQueryReturns(taglibQueries[5].query, taglibQueries[5].result); } public void testCellValue() { Result result = executeQuery( "select {[Measures].[Unit Sales],[Measures].[Store Sales]} on columns,\n" + " {[Gender].[M]} on rows\n" + "from Sales"); Cell cell = result.getCell(new int[] {0,0}); Object value = cell.getValue(); assertTrue(value instanceof Number); assertEquals(135215, ((Number) value).intValue()); cell = result.getCell(new int[] {1,0}); value = cell.getValue(); assertTrue(value instanceof Number); // Plato give 285011.12, Oracle gives 285011, MySQL gives 285964 (bug!) assertEquals(285011, ((Number) value).intValue()); } public void testDynamicFormat() { assertQueryReturns( "with member [Measures].[USales] as [Measures].[Unit Sales],\n" + " format_string = iif([Measures].[Unit Sales] > 50000, \"\\<b\\>#.00\\<\\/b\\>\", \"\\<i\\>#.00\\<\\/i\\>\")\n" + "select \n" + " {[Measures].[USales]} on columns,\n" + " {[Store Type].members} on rows\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Measures].[USales]}\n" + "Axis "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: <b>266773.00</b>\n" + "Row #1: <b>76837.00</b>\n" + "Row #2: <i>21333.00</i>\n" + "Row #3: \n" + "Row #4: <i>11491.00</i>\n" + "Row #5: <i>6557.00</i>\n" + "Row #6: <b>150555.00</b>\n")); } public void testFormatOfNulls() { assertQueryReturns( "with member [Measures].[Foo] as '([Measures].[Store Sales])',\n" + " format_string = '$#,##0.00;($#,##0.00);ZERO;NULL;Nil'\n" + "select\n" + " {[Measures].[Foo]} on columns,\n" + " {[Customers].[Country].members} on rows\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Foo]}\n" + "Axis "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[USA]}\n" + "Row #0: NULL\n" + "Row #1: NULL\n" + "Row #2: $565,238.13\n")); } /** * If a measure (in this case, <code>[Measures].[Sales Count]</code>) * occurs only within a format expression, bug 684593 causes an internal * error ("value not found") when the cell's formatted value is retrieved. */ public void testBug684593(FoodMartTestCase test) { test.assertQueryReturns( "with member [Measures].[USales] as '[Measures].[Unit Sales]',\n" + " format_string = iif([Measures].[Sales Count] > 30, \"#.00 good\",\"#.00 bad\")\n" + "select {[Measures].[USales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Crossjoin({[Promotion Media].[All Media].[Radio], [Promotion Media].[All Media].[TV], [Promotion Media]. [All Media].[Sunday Paper], [Promotion Media].[All Media].[Street Handout]}, [Product].[All Products].[Drink].Children) ON rows\n" + "from [Sales] where ([Time].[1997])", fold("Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[USales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[TV], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Sunday Paper], [Product].[All Products].[Drink].[Dairy]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Alcoholic Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Beverages]}\n" + "{[Promotion Media].[All Media].[Street Handout], [Product].[All Products].[Drink].[Dairy]}\n" + "Row #0: 75.00 bad\n" + "Row #0: 70.40\n" + "Row #0: 168.62\n" + "Row #1: 97.00 good\n" + "Row #1: 75.70\n" + "Row #1: 186.03\n" + "Row #2: 54.00 bad\n" + "Row #2: 36.75\n" + "Row #2: 89.03\n" + "Row #3: 76.00 bad\n" + "Row #3: 70.99\n" + "Row #3: 182.38\n" + "Row #4: 188.00 good\n" + "Row #4: 167.00\n" + "Row #4: 419.14\n" + "Row #5: 68.00 bad\n" + "Row #5: 45.19\n" + "Row #5: 119.55\n" + "Row #6: 148.00 good\n" + "Row #6: 128.97\n" + "Row #6: 316.88\n" + "Row #7: 197.00 good\n" + "Row #7: 161.81\n" + "Row #7: 399.58\n" + "Row #8: 85.00 bad\n" + "Row #8: 54.75\n" + "Row #8: 140.27\n" + "Row #9: 158.00 good\n" + "Row #9: 121.14\n" + "Row #9: 294.55\n" + "Row #10: 270.00 good\n" + "Row #10: 201.28\n" + "Row #10: 520.55\n" + "Row #11: 84.00 bad\n" + "Row #11: 50.26\n" + "Row #11: 128.32\n")); } /** This bug causes all of the format strings to be the same, because the * required expression [Measures].[Unit Sales] is not in the cache. */ public void testBug761196() { assertQueryReturns( "with member [Measures].[xxx] as '[Measures].[Store Sales]',\n" + " format_string = IIf([Measures].[Unit Sales] > 100000, \"AAA "select {[Measures].[xxx]} ON columns,\n" + " {[Product].[All Products].children} ON rows\n" + "from [Sales] where [Time].[1997]", fold("Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[xxx]}\n" + "Axis "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "Row #0: BBB48836.21\n" + "Row #1: AAA409035.59\n" + "Row #2: BBB107366.33\n")); } /** * Compound slicer causes {@link ClassCastException} */ public void testBug761952() { assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + " {[Gender].Children} ON rows\n" + "from [Sales]\n" + "where ([Time].[1997], [Customers])", fold("Axis "{[Time].[1997], [Customers].[All Customers]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n")); } /** * Query with distinct-count measure and no other measures gives * {@link ArrayIndexOutOfBoundsException} */ public void testBug804903() { CachePool.instance().flush(); assertQueryReturns( "select {[Measures].[Customer Count]} ON columns,\n" + " {([Promotion Media].[All Media], [Product].[All Products])} ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", fold("Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Customer Count]}\n" + "Axis "{[Promotion Media].[All Media], [Product].[All Products]}\n" + "Row #0: 5,581\n")); } /** Make sure that the "Store" cube is working. */ public void testStoreCube() { assertQueryReturns( "select {[Measures].members} on columns,\n" + " {[Store Type].members} on rows\n" + "from [Store]" + "where [Store].[USA].[CA]", fold("Axis "{[Store].[All Stores].[USA].[CA]}\n" + "Axis "{[Measures].[Store Sqft]}\n" + "{[Measures].[Grocery Sqft]}\n" + "Axis "{[Store Type].[All Store Types]}\n" + "{[Store Type].[All Store Types].[Deluxe Supermarket]}\n" + "{[Store Type].[All Store Types].[Gourmet Supermarket]}\n" + "{[Store Type].[All Store Types].[HeadQuarters]}\n" + "{[Store Type].[All Store Types].[Mid-Size Grocery]}\n" + "{[Store Type].[All Store Types].[Small Grocery]}\n" + "{[Store Type].[All Store Types].[Supermarket]}\n" + "Row #0: 69,764\n" + "Row #0: 44,868\n" + "Row #1: \n" + "Row #1: \n" + "Row #2: 23,688\n" + "Row #2: 15,337\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: 22,478\n" + "Row #5: 15,321\n" + "Row #6: 23,598\n" + "Row #6: 14,210\n")); } public void testSchemaLevelTableIsBad() { // todo: <Level table="nonexistentTable"> } public void testSchemaLevelTableInAnotherHierarchy() { // todo: // <Cube> // <Hierarchy name="h1"><Table name="t1"/></Hierarchy> // <Hierarchy name="h2"><Table name="t2"/><Level tableName="t1"/></Hierarchy> // </Cube> } public void testSchemaLevelWithViewSpecifiesTable() { // todo: // <Hierarchy> // <View><SQL dialect="generic">select * from emp</SQL></View> // <Level tableName="emp"/> // </hierarchy> // Should get error that tablename is not allowed } public void testSchemaLevelOrdinalInOtherTable() { // todo: // Hierarchy is based upon a join. // Level's name expression is in a different table than its ordinal. } public void testSchemaTopLevelNotUnique() { // todo: // Should get error if the top level of a hierarchy does not have // uniqueNames="true" } /** * Bug 645744 happens when getting the children of a member crosses a table * boundary. The symptom */ public void testBug645744() { // minimal test case assertQueryReturns( "select {[Measures].[Unit Sales]} ON columns,\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].children} ON rows\n" + "from [Sales]", fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Excellent]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Fabulous]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Skinner]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Token]}\n" + "{[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks].[Washington]}\n" + "Row #0: 468\n" + "Row #1: 469\n" + "Row #2: 506\n" + "Row #3: 466\n" + "Row #4: 560\n")); // shorter test case executeQuery("select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,"+ "ToggleDrillState({"+ "([Promotion Media].[All Media].[Radio], [Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks])"+ "}, {[Product].[All Products].[Drink].[Beverages].[Drinks].[Flavored Drinks]}) ON rows "+ "from [Sales] where ([Time].[1997])"); } /** * The bug happened when a cell which was in cache was compared with a cell * which was not in cache. The compare method could not deal with the * {@link RuntimeException} which indicates that the cell is not in cache. */ public void testBug636687() { executeQuery("select {[Measures].[Unit Sales], [Measures].[Store Cost],[Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].Children}, {[Product].[All Products].[Drink].[Beverages]}), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); executeQuery("select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns, " + "Order(" + "{([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Alcoholic Beverages]), " + "([Store].[All Stores].[USA].[WA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Diego], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA].[Los Angeles], [Product].[All Products].[Drink].[Beverages]), " + "Crossjoin({[Store].[All Stores].[USA].[CA].[Los Angeles]}, {[Product].[All Products].[Drink].[Beverages].Children}), " + "([Store].[All Stores].[USA].[CA].[Beverly Hills], [Product].[All Products].[Drink].[Beverages]), " + "([Store].[All Stores].[USA].[CA], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[OR], [Product].[All Products].[Drink].[Dairy]), " + "([Store].[All Stores].[USA].[CA].[San Francisco], [Product].[All Products].[Drink].[Beverages])}, " + "[Measures].[Store Cost], BDESC) ON rows " + "from [Sales] " + "where ([Time].[1997])"); } /** Bug 769114: Internal error ("not found") when executing * Order(TopCount). */ public void testBug769114() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} ON columns,\n" + " Order(TopCount({[Product].[Product Category].Members}, 10.0, [Measures].[Unit Sales]), [Measures].[Store Sales], ASC) ON rows\n" + "from [Sales]\n" + "where [Time].[1997]", fold("Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Cost]}\n" + "{[Measures].[Store Sales]}\n" + "Axis "{[Product].[All Products].[Food].[Baked Goods].[Bread]}\n" + "{[Product].[All Products].[Food].[Deli].[Meat]}\n" + "{[Product].[All Products].[Food].[Dairy].[Dairy]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Baking Goods]}\n" + "{[Product].[All Products].[Food].[Baking Goods].[Jams and Jellies]}\n" + "{[Product].[All Products].[Food].[Canned Foods].[Canned Soup]}\n" + "{[Product].[All Products].[Food].[Frozen Foods].[Vegetables]}\n" + "{[Product].[All Products].[Food].[Snack Foods].[Snack Foods]}\n" + "{[Product].[All Products].[Food].[Produce].[Fruit]}\n" + "{[Product].[All Products].[Food].[Produce].[Vegetables]}\n" + "Row #0: 7,870\n" + "Row #0: 6,564.09\n" + "Row #0: 16,455.43\n" + "Row #1: 9,433\n" + "Row #1: 8,215.81\n" + "Row #1: 20,616.29\n" + "Row #2: 12,885\n" + "Row #2: 12,228.85\n" + "Row #2: 30,508.85\n" + "Row #3: 8,357\n" + "Row #3: 6,123.32\n" + "Row #3: 15,446.69\n" + "Row #4: 11,888\n" + "Row #4: 9,247.29\n" + "Row #4: 23,223.72\n" + "Row #5: 8,006\n" + "Row #5: 6,408.29\n" + "Row #5: 15,966.10\n" + "Row #6: 6,984\n" + "Row #6: 5,885.05\n" + "Row #6: 14,769.82\n" + "Row #7: 30,545\n" + "Row #7: 26,963.34\n" + "Row #7: 67,609.82\n" + "Row #8: 11,767\n" + "Row #8: 10,312.77\n" + "Row #8: 25,816.13\n" + "Row #9: 20,739\n" + "Row #9: 18,048.81\n" + "Row #9: 45,185.41\n")); } /** * Bug 793616: Deeply nested UNION function takes forever to validate. * (Problem was that each argument of a function was validated twice, hence * the validation time was <code>O(2 ^ depth)</code>.) */ public void _testBug793616() { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { // Don't run this test if dependency-checking is enabled. // Dependency checking will hugely slow down evaluation, and give // the false impression that the validation performance bug has // returned. return; } final long start = System.currentTimeMillis(); Connection connection = getTestContext().getFoodMartConnection(false); final String queryString = fold( "select {[Measures].[Unit Sales],\n" + " [Measures].[Store Cost],\n" + " [Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union(Union\n" + "({([Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])},\n" + " Crossjoin ([Gender].[All Gender].Children,\n" + " {([Marital Status].[All Marital Status],\n" + " [Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({[Gender].[All Gender].[F]},\n" + " [Marital Status].[All Marital Status].Children),\n" + " {([Customers].[All Customers],\n" + " [Product].[All Products])})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[M])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[M], [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(\n" + " Crossjoin({([Gender].[All Gender].[F], [Marital Status].[All Marital Status].[S])}, [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status].[S],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin(Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status])},\n" + " [Customers].[All Customers].[USA].Children),\n" + " {[Product].[All Products]})),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[CA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[OR])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA].[WA])},\n" + " [Product].[All Products].Children)),\n" + " Crossjoin ({([Gender].[All Gender].[F],\n" + " [Marital Status].[All Marital Status],\n" + " [Customers].[All Customers].[USA])},\n" + " [Product].[All Products].Children))) ON rows from [Sales] where [Time].[1997]"); Query query = connection.parseQuery(queryString); // If this call took longer than 10 seconds, the performance bug has // probably resurfaced again. final long afterParseMillis = System.currentTimeMillis(); final long afterParseNonDbMillis = afterParseMillis - Util.dbTimeMillis(); final long parseMillis = afterParseMillis - start; assertTrue("performance problem: parse took " + parseMillis + " milliseconds", parseMillis <= 10000); Result result = connection.execute(query); assertEquals(59, result.getAxes()[1].positions.length); // If this call took longer than 10 seconds, // or 2 seconds exclusing db access, // the performance bug has // probably resurfaced again. final long afterExecMillis = System.currentTimeMillis(); final long afterExecNonDbMillis = afterExecMillis - Util.dbTimeMillis(); final long execNonDbMillis = afterExecNonDbMillis - afterParseNonDbMillis; final long execMillis = (afterExecMillis - afterParseMillis); assertTrue("performance problem: execute took " + execMillis + " milliseconds, " + execNonDbMillis + " milliseconds excluding db", execNonDbMillis <= 2000 && execMillis <= 30000); } public void testCatalogHierarchyBasedOnView() { RolapConnection conn = (RolapConnection) getConnection(); String jdbc_url = conn.getConnectInfo().get("Jdbc"); if (jdbc_url.toLowerCase().indexOf("mysql") >= 0 ) { return; // Mysql cannot handle subselect } Schema schema = getConnection().getSchema(); final Cube salesCube = schema.lookupCube("Sales", true); schema.createDimension( salesCube, fold("<Dimension name=\"Gender2\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\" primaryKey=\"customer_id\">\n" + " <View alias=\"gender2\">\n" + " <SQL dialect=\"generic\">\n" + " <![CDATA[SELECT * FROM customer]]>\n" + " </SQL>\n" + " <SQL dialect=\"oracle\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " <SQL dialect=\"derby\">\n" + " <![CDATA[SELECT * FROM \"customer\"]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); final Axis axis = getTestContext().executeAxis("[Gender2].members"); assertEquals(fold( "[Gender2].[All Gender]\n" + "[Gender2].[All Gender].[F]\n" + "[Gender2].[All Gender].[M]"), TestContext.toString(axis.positions)); } /** * Run a query against a large hierarchy, to make sure that we can generate * joins correctly. This probably won't work in MySQL. */ public void testCatalogHierarchyBasedOnView2() { RolapConnection conn = (RolapConnection) getConnection(); String jdbc_url = conn.getConnectInfo().get("Jdbc"); if (jdbc_url.toLowerCase().indexOf("mysql") >= 0) { return; // Mysql cannot handle subselect } Schema schema = getConnection().getSchema(); final Cube salesCube = schema.lookupCube("Sales", true); schema.createDimension( salesCube, fold("<Dimension name=\"ProductView\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\" primaryKeyTable=\"productView\">\n" + " <View alias=\"productView\">\n" + " <SQL dialect=\"db2\"><![CDATA[\n" + "SELECT *\n" + "FROM product, product_class\n" + "WHERE product.product_class_id = product_class.product_class_id\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"mssql\"><![CDATA[\n" + "SELECT \"product\".\"product_id\",\n" + "\"product\".\"brand_name\",\n" + "\"product\".\"product_name\",\n" + "\"product\".\"SKU\",\n" + "\"product\".\"SRP\",\n" + "\"product\".\"gross_weight\",\n" + "\"product\".\"net_weight\",\n" + "\"product\".\"recyclable_package\",\n" + "\"product\".\"low_fat\",\n" + "\"product\".\"units_per_case\",\n" + "\"product\".\"cases_per_pallet\",\n" + "\"product\".\"shelf_width\",\n" + "\"product\".\"shelf_height\",\n" + "\"product\".\"shelf_depth\",\n" + "\"product_class\".\"product_class_id\",\n" + "\"product_class\".\"product_subcategory\",\n" + "\"product_class\".\"product_category\",\n" + "\"product_class\".\"product_department\",\n" + "\"product_class\".\"product_family\"\n" + "FROM \"product\" inner join \"product_class\"\n" + "ON \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " <SQL dialect=\"generic\"><![CDATA[\n" + "SELECT *\n" + "FROM \"product\", \"product_class\"\n" + "WHERE \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\"\n" + "]]>\n" + " </SQL>\n" + " </View>\n" + " <Level name=\"Product Family\" column=\"product_family\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" column=\"product_department\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" column=\"product_category\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" column=\"product_subcategory\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" column=\"product_name\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); assertQueryReturns( "select {[Measures].[Unit Sales]} on columns,\n" + " {[ProductView].[Drink].[Beverages].children} on rows\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[ProductView].[All ProductViews].[Drink].[Beverages].[Carbonated Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Drinks]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Hot Beverages]}\n" + "{[ProductView].[All ProductViews].[Drink].[Beverages].[Pure Juice Beverages]}\n" + "Row #0: 3,407\n" + "Row #1: 2,469\n" + "Row #2: 4,301\n" + "Row #3: 3,396\n")); } public void testCountDistinct() { assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on columns,\n" + " {[Gender].members} on rows\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Axis "{[Gender].[All Gender]}\n" + "{[Gender].[All Gender].[F]}\n" + "{[Gender].[All Gender].[M]}\n" + "Row #0: 266,773\n" + "Row #0: 5,581\n" + "Row #1: 131,558\n" + "Row #1: 2,755\n" + "Row #2: 135,215\n" + "Row #2: 2,826\n")); } /** * Turn off aggregate caching and run query with both use of aggregate * tables on and off - should result in the same answer. * Note that if the "mondrian.rolap.aggregates.Read" property is not true, * then no aggregate tables is be read in any event. */ public void testCountDistinctAgg() { final MondrianProperties properties = MondrianProperties.instance(); boolean use_agg_orig = properties.UseAggregates.get(); boolean do_caching_orig = properties.DisableCaching.get(); // turn off caching properties.DisableCaching.setString("true"); assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Time].[1997].[Q1].[1]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n")); if (use_agg_orig) { properties.UseAggregates.setString("false"); } else { properties.UseAggregates.setString("true"); } assertQueryReturns( "select {[Measures].[Unit Sales], [Measures].[Customer Count]} on rows,\n" + "NON EMPTY {[Time].[1997].[Q1].[1]} ON COLUMNS\n" + "from Sales", fold("Axis "{}\n" + "Axis "{[Time].[1997].[Q1].[1]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Customer Count]}\n" + "Row #0: 21,628\n" + "Row #1: 1,396\n")); if (use_agg_orig) { properties.UseAggregates.setString("true"); } else { properties.UseAggregates.setString("false"); } if (do_caching_orig) { properties.DisableCaching.setString("true"); } else { properties.DisableCaching.setString("false"); } } /** * * There are cross database order issues in this test. * * MySQL and Access show the rows as: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store size>] * * Postgres shows: * * [Store Size in SQFT].[All Store Size in SQFTs] * [Store Size in SQFT].[All Store Size in SQFTs].[<each distinct store size>] * [Store Size in SQFT].[All Store Size in SQFTs].[null] * * The test failure is due to some inherent differences in the way Postgres orders NULLs in a result set, * compared with MySQL and Access. * * From the MySQL 4.X manual: * * When doing an ORDER BY, NULL values are presented first if you do * ORDER BY ... ASC and last if you do ORDER BY ... DESC. * * From the Postgres 8.0 manual: * * The null value sorts higher than any other value. In other words, * with ascending sort order, null values sort at the end, and with * descending sort order, null values sort at the beginning. * * Oracle also sorts nulls high by default. * * So, this test has expected results that vary depending on whether * the database is being used sorts nulls high or low. * */ public void testMemberWithNullKey() { Result result = executeQuery( "select {[Measures].[Unit Sales]} on columns,\n" + "{[Store Size in SQFT].members} on rows\n" + "from Sales"); String resultString = TestContext.toString(result); resultString = Pattern.compile("\\.0\\]").matcher(resultString).replaceAll("]"); // The members function hierarchizes its results, so nulls should // sort high, regardless of DBMS. Note that Oracle's driver says that // NULLs sort low, but it's lying. final boolean nullsSortHigh = false; int row = 0; final String expected = fold( "Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Store Size in SQFT].[All Store Size in SQFTs]}\n" + // null is at the start in order under DBMSs that sort null low (!nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "{[Store Size in SQFT].[All Store Size in SQFTs].[20319]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[21215]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[22478]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23112]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23593]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23598]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23688]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[23759]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[24597]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[27694]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[28206]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30268]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30584]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[30797]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[33858]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34452]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[34791]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[36509]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[38382]}\n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[39696]}\n" + // null is at the end in order for DBMSs that sort nulls high (nullsSortHigh ? "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" : "") + "Row #" + row++ + ": 266,773\n" + (!nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : "" ) + "Row #" + row++ + ": 26,079\n" + "Row #" + row++ + ": 25,011\n" + "Row #" + row++ + ": 2,117\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 25,663\n" + "Row #" + row++ + ": 21,333\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 41,580\n" + "Row #" + row++ + ": 2,237\n" + "Row #" + row++ + ": 23,591\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 35,257\n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": \n" + "Row #" + row++ + ": 24,576\n" + (nullsSortHigh ? "Row #" + row++ + ": 39,329\n" : "" )); assertEquals(expected, resultString); } /** * Slicer contains <code>[Promotion Media].[Daily Paper]</code>, but * filter expression is in terms of <code>[Promotion Media].[Radio]</code>. */ public void testSlicerOverride() { assertQueryReturns( "with member [Measures].[Radio Unit Sales] as \n" + " '([Measures].[Unit Sales], [Promotion Media].[Radio])'\n" + "select {[Measures].[Unit Sales], [Measures].[Radio Unit Sales]} on columns,\n" + " filter([Product].[Product Department].members, [Promotion Media].[Radio] > 50) on rows\n" + "from Sales\n" + "where ([Promotion Media].[Daily Paper], [Time].[1997].[Q1])", fold("Axis "{[Promotion Media].[All Media].[Daily Paper], [Time].[1997].[Q1]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Radio Unit Sales]}\n" + "Axis "{[Product].[All Products].[Food].[Produce]}\n" + "{[Product].[All Products].[Food].[Snack Foods]}\n" + "Row #0: 692\n" + "Row #0: 87\n" + "Row #1: 447\n" + "Row #1: 63\n")); } public void testMembersOfLargeDimensionTheHardWay() { final MondrianProperties properties = MondrianProperties.instance(); int old = properties.LargeDimensionThreshold.get(); try { // prevent a CacheMemberReader from kicking in MondrianProperties.instance().LargeDimensionThreshold.set(1); final Connection connection = TestContext.instance().getFoodMartConnection(true); String queryString = fold( "select {[Measures].[Unit Sales]} on columns,\n" + "{[Customers].members} on rows\n" + "from Sales"); Query query = connection.parseQuery(queryString); Result result = connection.execute(query); assertEquals(10407, result.getAxes()[1].positions.length); } finally { MondrianProperties.instance().LargeDimensionThreshold.set(old); } } public void testUnparse() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Rendite] as \n" + " '(([Measures].[Store Sales] - [Measures].[Store Cost])) / [Measures].[Store Cost]',\n" + " format_string = iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 > \n" + " Parameter (\"UpperLimit\", NUMERIC, 151, \"Obere Grenze\"), \n" + " \"|#.00%|arrow='up'\",\n" + " iif(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost] * 100 < \n" + " Parameter(\"LowerLimit\", NUMERIC, 150, \"Untere Grenze\"),\n" + " \"|#.00%|arrow='down'\",\n" + " \"|#.00%|arrow='right'\"))\n" + "select {[Measures].members} on columns\n" + "from Sales"); final String s = query.toString(); // Parentheses are added to reflect operator precedence, but that's ok. // Note that the doubled parentheses in line #2 of the query have been // reduced to a single level. assertEquals( fold("with member [Measures].[Rendite] as '(([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost])', " + "format_string = IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) > Parameter(\"UpperLimit\", NUMERIC, 151.0, \"Obere Grenze\")), " + "\"|#.00%|arrow='up'\", " + "IIf((((([Measures].[Store Sales] - [Measures].[Store Cost]) / [Measures].[Store Cost]) * 100.0) < Parameter(\"LowerLimit\", NUMERIC, 150.0, \"Untere Grenze\")), " + "\"|#.00%|arrow='down'\", \"|#.00%|arrow='right'\"))\n" + "select {[Measures].Members} ON COLUMNS\n" + "from [Sales]\n"), s); } public void testUnparse2() { Connection connection = getConnection(); Query query = connection.parseQuery( "with member [Measures].[Foo] as '1', " + "format_string='##0.00', " + "funny=IIf(1=1,\"x\"\"y\",\"foo\") " + "select {[Measures].[Foo]} on columns from Sales"); final String s = query.toString(); // The "format_string" property, a string literal, is now delimited by // double-quotes. This won't work in MSOLAP, but for Mondrian it's // consistent with the fact that property values are expressions, // not enclosed in single-quotes. assertEquals(fold( "with member [Measures].[Foo] as '1.0', " + "format_string = \"##0.00\", " + "funny = IIf((1.0 = 1.0), \"x\"\"y\", \"foo\")\n" + "select {[Measures].[Foo]} ON COLUMNS\n" + "from [Sales]\n"), s); } /** * Basically, the LookupCube function can evaluate a single MDX statement * against a cube other than the cube currently indicated by query context * to retrieve a single string or numeric result. * * <p>For example, the Budget cube in the FoodMart 2000 database contains * budget information that can be displayed by store. The Sales cube in the * FoodMart 2000 database contains sales information that can be displayed * by store. Since no virtual cube exists in the FoodMart 2000 database that * joins the Sales and Budget cubes together, comparing the two sets of * figures would be difficult at best. * * <p><b>Note<b> In many situations a virtual cube can be used to integrate * data from multiple cubes, which will often provide a simpler and more * efficient solution than the LookupCube function. This example uses the * LookupCube function for purposes of illustration. * * <p>The following MDX query, however, uses the LookupCube function to * retrieve unit sales information for each store from the Sales cube, * presenting it side by side with the budget information from the Budget * cube. */ public void _testLookupCube() { assertQueryReturns( "WITH MEMBER Measures.[Store Unit Sales] AS \n" + " 'LookupCube(\"Sales\", \"(\" + MemberToStr(Store.CurrentMember) + \", Measures.[Unit Sales])\")'\n" + "SELECT\n" + " {Measures.Amount, Measures.[Store Unit Sales]} ON COLUMNS,\n" + " Store.CA.CHILDREN ON ROWS\n" + "FROM Budget", ""); } /** * <p>Basket analysis is a topic better suited to data mining discussions, but * some basic forms of basket analysis can be handled through the use of MDX * queries. * * <p>For example, one method of basket analysis groups customers based on * qualification. In the following example, a qualified customer is one who * has more than $10,000 in store sales or more than 10 unit sales. The * following table illustrates such a report, run against the Sales cube in * FoodMart 2000 with qualified customers grouped by the Country and State * Province levels of the Customers dimension. The count and store sales * total of qualified customers is represented by the Qualified Count and * Qualified Sales columns, respectively. * * <p>To accomplish this basic form of basket analysis, the following MDX * query constructs two calculated members. The first calculated member uses * the MDX Count, Filter, and Descendants functions to create the Qualified * Count column, while the second calculated member uses the MDX Sum, * Filter, and Descendants functions to create the Qualified Sales column. * * <p>The key to this MDX query is the use of Filter and Descendants together * to screen out non-qualified customers. Once screened out, the Sum and * Count MDX functions can then be used to provide aggregation data only on * qualified customers. */ public void testBasketAnalysis() { assertQueryReturns( "WITH MEMBER [Measures].[Qualified Count] AS\n" + " 'COUNT(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10))'\n" + "MEMBER [Measures].[Qualified Sales] AS\n" + " 'SUM(FILTER(DESCENDANTS(Customers.CURRENTMEMBER, [Customers].[Name]),\n" + " ([Measures].[Store Sales]) > 10000 OR ([Measures].[Unit Sales]) > 10),\n" + " ([Measures].[Store Sales]))'\n" + "SELECT {[Measures].[Qualified Count], [Measures].[Qualified Sales]} ON COLUMNS,\n" + " DESCENDANTS([Customers].[All Customers], [State Province], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Qualified Count]}\n" + "{[Measures].[Qualified Sales]}\n" + "Axis "{[Customers].[All Customers]}\n" + "{[Customers].[All Customers].[Canada]}\n" + "{[Customers].[All Customers].[Canada].[BC]}\n" + "{[Customers].[All Customers].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[DF]}\n" + "{[Customers].[All Customers].[Mexico].[Guerrero]}\n" + "{[Customers].[All Customers].[Mexico].[Jalisco]}\n" + "{[Customers].[All Customers].[Mexico].[Mexico]}\n" + "{[Customers].[All Customers].[Mexico].[Oaxaca]}\n" + "{[Customers].[All Customers].[Mexico].[Sinaloa]}\n" + "{[Customers].[All Customers].[Mexico].[Veracruz]}\n" + "{[Customers].[All Customers].[Mexico].[Yucatan]}\n" + "{[Customers].[All Customers].[Mexico].[Zacatecas]}\n" + "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[WA]}\n" + "Row #0: 4,719.00\n" + "Row #0: 553,587.77\n" + "Row #1: .00\n" + "Row #1: \n" + "Row #2: .00\n" + "Row #2: \n" + "Row #3: .00\n" + "Row #3: \n" + "Row #4: .00\n" + "Row #4: \n" + "Row #5: .00\n" + "Row #5: \n" + "Row #6: .00\n" + "Row #6: \n" + "Row #7: .00\n" + "Row #7: \n" + "Row #8: .00\n" + "Row #8: \n" + "Row #9: .00\n" + "Row #9: \n" + "Row #10: .00\n" + "Row #10: \n" + "Row #11: .00\n" + "Row #11: \n" + "Row #12: .00\n" + "Row #12: \n" + "Row #13: 4,719.00\n" + "Row #13: 553,587.77\n" + "Row #14: 2,149.00\n" + "Row #14: 151,509.69\n" + "Row #15: 1,008.00\n" + "Row #15: 141,899.84\n" + "Row #16: 1,562.00\n" + "Row #16: 260,178.24\n")); } /** * Flushes the cache then runs {@link #testBasketAnalysis}, because this * test has been known to fail when run standalone. */ public void testBasketAnalysisAfterFlush() { CachePool.instance().flush(); testBasketAnalysis(); } /** * <b>How Can I Perform Complex String Comparisons?</b> * * <p>MDX can handle basic string comparisons, but does not include complex * string comparison and manipulation functions, for example, for finding * substrings in strings or for supporting case-insensitive string * comparisons. However, since MDX can take advantage of external function * libraries, this question is easily resolved using string manipulation * and comparison functions from the Microsoft Visual Basic for * Applications (VBA) external function library. * * <p>For example, you want to report the unit sales of all fruit-based * products -- not only the sales of fruit, but canned fruit, fruit snacks, * fruit juices, and so on. By using the LCase and InStr VBA functions, the * following results are easily accomplished in a single MDX query, without * complex set construction or explicit member names within the query. * * <p>The following MDX query demonstrates how to achieve the results * displayed in the previous table. For each member in the Product * dimension, the name of the member is converted to lowercase using the * LCase VBA function. Then, the InStr VBA function is used to discover * whether or not the name contains the word "fruit". This information is * used to then construct a set, using the Filter MDX function, from only * those members from the Product dimension that contain the substring * "fruit" in their names. */ public void _testStringComparisons() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " FILTER([Product].[Product Name].MEMBERS,\n" + " INSTR(LCASE([Product].CURRENTMEMBER.NAME), \"fruit\") <> 0) ON ROWS \n" + "FROM Sales", ""); } /** * <b>How Can I Show Percentages as Measures?</b> * * <p>Another common business question easily answered through MDX is the * display of percent values created as available measures. * * <p>For example, the Sales cube in the FoodMart 2000 database contains * unit sales for each store in a given city, state, and country, organized * along the Sales dimension. A report is requested to show, for * California, the percentage of total unit sales attained by each city * with a store. The results are illustrated in the following table. * * <p>Because the parent of a member is typically another, aggregated * member in a regular dimension, this is easily achieved by the * construction of a calculated member, as demonstrated in the following MDX * query, using the CurrentMember and Parent MDX functions. */ public void testPercentagesAsMeasures() { assertQueryReturns( // todo: "Store.[USA].[CA]" should be "Store.CA" "WITH MEMBER Measures.[Unit Sales Percent] AS\n" + " '((Store.CURRENTMEMBER, Measures.[Unit Sales]) /\n" + " (Store.CURRENTMEMBER.PARENT, Measures.[Unit Sales])) ',\n" + " FORMAT_STRING = 'Percent'\n" + "SELECT {Measures.[Unit Sales], Measures.[Unit Sales Percent]} ON COLUMNS,\n" + " ORDER(DESCENDANTS(Store.[USA].[CA], Store.[Store City], SELF), \n" + " [Measures].[Unit Sales], ASC) ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "{[Measures].[Unit Sales Percent]}\n" + "Axis "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 2,117\n" + "Row #1: 2.83%\n" + "Row #2: 21,333\n" + "Row #2: 28.54%\n" + "Row #3: 25,635\n" + "Row #3: 34.30%\n" + "Row #4: 25,663\n" + "Row #4: 34.33%\n")); } /** * <b>How Can I Show Cumulative Sums as Measures?</b> * * <p>Another common business request, cumulative sums, is useful for * business reporting purposes. However, since aggregations are handled in a * hierarchical fashion, cumulative sums present some unique challenges in * Analysis Services. * * <p>The best way to create a cumulative sum is as a calculated measure in * MDX, using the Rank, Head, Order, and Sum MDX functions together. * * <p>For example, the following table illustrates a report that shows two * views of employee count in all stores and cities in California, sorted * by employee count. The first column shows the aggregated counts for each * store and city, while the second column shows aggregated counts for each * store, but cumulative counts for each city. * * <p>The cumulative number of employees for San Diego represents the value * of both Los Angeles and San Diego, the value for Beverly Hills represents * the cumulative total of Los Angeles, San Diego, and Beverly Hills, and so * on. * * <p>Since the members within the state of California have been ordered * from highest to lowest number of employees, this form of cumulative sum * measure provides a form of pareto analysis within each state. * * <p>To support this, the Order function is first used to reorder members * accordingly for both the Rank and Head functions. Once reordered, the * Rank function is used to supply the ranking of each tuple within the * reordered set of members, progressing as each member in the Store * dimension is examined. The value is then used to determine the number of * tuples to retrieve from the set of reordered members using the Head * function. Finally, the retrieved members are then added together using * the Sum function to obtain a cumulative sum. The following MDX query * demonstrates how all of this works in concert to provide cumulative * sums. * * <p>As an aside, a named set cannot be used in this situation to replace * the duplicate Order function calls. Named sets are evaluated once, when * a query is parsed -- since the set can change based on the fact that the * set can be different for each store member because the set is evaluated * for the children of multiple parents, the set does not change with * respect to its use in the Sum function. Since the named set is only * evaluated once, it would not satisfy the needs of this query. */ public void _testCumlativeSums() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "Store.CA"; implement "AS" "WITH MEMBER Measures.[Cumulative No of Employees] AS\n" + " 'SUM(HEAD(ORDER({[Store].Siblings}, [Measures].[Number of Employees], BDESC) AS OrderedSiblings,\n" + " RANK([Store], OrderedSiblings)),\n" + " [Measures].[Number of Employees])'\n" + "SELECT {[Measures].[Number of Employees], [Measures].[Cumulative No of Employees]} ON COLUMNS,\n" + " ORDER(DESCENDANTS([Store].[USA].[CA], [Store State], AFTER), \n" + " [Measures].[Number of Employees], BDESC) ON ROWS\n" + "FROM HR", ""); } /** * <b>How Can I Implement a Logical AND or OR Condition in a WHERE * Clause?</b> * * <p>For SQL users, the use of AND and OR logical operators in the WHERE * clause of a SQL statement is an essential tool for constructing business * queries. However, the WHERE clause of an MDX statement serves a * slightly different purpose, and understanding how the WHERE clause is * used in MDX can assist in constructing such business queries. * * <p>The WHERE clause in MDX is used to further restrict the results of * an MDX query, in effect providing another dimension on which the results * of the query are further sliced. As such, only expressions that resolve * to a single tuple are allowed. The WHERE clause implicitly supports a * logical AND operation involving members across different dimensions, by * including the members as part of a tuple. To support logical AND * operations involving members within a single dimensions, as well as * logical OR operations, a calculated member needs to be defined in * addition to the use of the WHERE clause. * * <p>For example, the following MDX query illustrates the use of a * calculated member to support a logical OR. The query returns unit sales * by quarter and year for all food and drink related products sold in 1997, * run against the Sales cube in the FoodMart 2000 database. * * <p>The calculated member simply adds the values of the Unit Sales * measure for the Food and the Drink levels of the Product dimension * together. The WHERE clause is then used to restrict return of * information only to the calculated member, effectively implementing a * logical OR to return information for all time periods that contain unit * sales values for either food, drink, or both types of products. * * <p>You can use the Aggregate function in similar situations where all * measures are not aggregated by summing. To return the same results in the * above example using the Aggregate function, replace the definition for * the calculated member with this definition: * * <blockquote><pre>'Aggregate({[Product].[Food], [Product].[Drink]})'</pre></blockquote> */ public void testLogicalOps() { assertQueryReturns( "WITH MEMBER [Product].[Food OR Drink] AS\n" + " '([Product].[Food], Measures.[Unit Sales]) + ([Product].[Drink], Measures.[Unit Sales])'\n" + "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS(Time.[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Food OR Drink]", fold("Axis "{[Product].[Food OR Drink]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 216,537\n" + "Row #1: 53,785\n" + "Row #2: 50,720\n" + "Row #3: 53,505\n" + "Row #4: 58,527\n")); } /** * <p>A logical AND, by contrast, can be supported by using two different * techniques. If the members used to construct the logical AND reside on * different dimensions, all that is required is a WHERE clause that uses * a tuple representing all involved members. The following MDX query uses a * WHERE clause that effectively restricts the query to retrieve unit * sales for drink products in the USA, shown by quarter and year for 1997. */ public void testLogicalAnd() { assertQueryReturns( // todo: "[Store].USA" should be "[Store].[USA]" "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON ROWS\n" + "FROM Sales\n" + "WHERE ([Product].[Drink], [Store].[USA])", fold("Axis "{[Product].[All Products].[Drink], [Store].[All Stores].[USA]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Time].[1997]}\n" + "{[Time].[1997].[Q1]}\n" + "{[Time].[1997].[Q2]}\n" + "{[Time].[1997].[Q3]}\n" + "{[Time].[1997].[Q4]}\n" + "Row #0: 24,597\n" + "Row #1: 5,976\n" + "Row #2: 5,895\n" + "Row #3: 6,065\n" + "Row #4: 6,661\n")); } /** * <p>The WHERE clause in the previous MDX query effectively provides a * logical AND operator, in which all unit sales for 1997 are returned only * for drink products and only for those sold in stores in the USA. * * <p>If the members used to construct the logical AND condition reside on * the same dimension, you can use a calculated member or a named set to * filter out the unwanted members, as demonstrated in the following MDX * query. * * <p>The named set, [Good AND Pearl Stores], restricts the displayed unit * sales totals only to those stores that have sold both Good products and * Pearl products. */ public void _testSet() { assertQueryReturns( "WITH SET [Good AND Pearl Stores] AS\n" + " 'FILTER(Store.Members,\n" + " ([Product].[Good], Measures.[Unit Sales]) > 0 AND \n" + " ([Product].[Pearl], Measures.[Unit Sales]) > 0)'\n" + "SELECT DESCENDANTS([Time].[1997], [Quarter], SELF_AND_BEFORE) ON COLUMNS,\n" + " [Good AND Pearl Stores] ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Custom Member Properties in MDX?</b> * * <p>Member properties are a good way of adding secondary business * information to members in a dimension. However, getting that information * out can be confusing -- member properties are not readily apparent in a * typical MDX query. * * <p>Member properties can be retrieved in one of two ways. The easiest * and most used method of retrieving member properties is to use the * DIMENSION PROPERTIES MDX statement when constructing an axis in an MDX * query. * * <p>For example, a member property in the Store dimension in the FoodMart * 2000 database details the total square feet for each store. The following * MDX query can retrieve this member property as part of the returned * cellset. */ public void testCustomMemberProperties() { assertQueryReturns( "SELECT {[Measures].[Units Shipped], [Measures].[Units Ordered]} ON COLUMNS,\n" + " NON EMPTY [Store].[Store Name].MEMBERS\n" + " DIMENSION PROPERTIES [Store].[Store Name].[Store Sqft] ON ROWS\n" + "FROM Warehouse", fold( "Axis "{}\n" + "Axis "{[Measures].[Units Shipped]}\n" + "{[Measures].[Units Ordered]}\n" + "Axis "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: 10759.0\n" + "Row #0: 11699.0\n" + "Row #1: 24587.0\n" + "Row #1: 26463.0\n" + "Row #2: 23835.0\n" + "Row #2: 26270.0\n" + "Row #3: 1696.0\n" + "Row #3: 1875.0\n" + "Row #4: 8515.0\n" + "Row #4: 9109.0\n" + "Row #5: 32393.0\n" + "Row #5: 35797.0\n" + "Row #6: 2348.0\n" + "Row #6: 2454.0\n" + "Row #7: 22734.0\n" + "Row #7: 24610.0\n" + "Row #8: 24110.0\n" + "Row #8: 26703.0\n" + "Row #9: 11889.0\n" + "Row #9: 12828.0\n" + "Row #10: 32411.0\n" + "Row #10: 35930.0\n" + "Row #11: 1860.0\n" + "Row #11: 2074.0\n" + "Row #12: 10589.0\n" + "Row #12: 11426.0\n")); } /** * <p>The drawback to using the DIMENSION PROPERTIES statement is that, * for most client applications, the member property is not readily * apparent. If the previous MDX query is executed in the MDX sample * application shipped with SQL Server 2000 Analysis Services, for example, * you must double-click the name of the member in the grid to open the * Member Properties dialog box, which displays all of the member properties * shipped as part of the cellset, including the [Store].[Store Name].[Store * Sqft] member property. * * <p>The other method of retrieving member properties involves the creation * of a calculated member based on the member property. The following MDX * query brings back the total square feet for each store as a measure, * included in the COLUMNS axis. * * <p>The [Store SqFt] measure is constructed with the Properties MDX * function to retrieve the [Store SQFT] member property for each member in * the Store dimension. The benefit to this technique is that the calculated * member is readily apparent and easily accessible in client applications * that do not support member properties. */ public void _testMemberPropertyAsCalcMember() { assertQueryReturns( // todo: implement <member>.PROPERTIES "WITH MEMBER Measures.[Store SqFt] AS '[Store].CURRENTMEMBER.PROPERTIES(\"Store SQFT\")'\n" + "SELECT { [Measures].[Store SQFT], [Measures].[Units Shipped], [Measures].[Units Ordered] } ON COLUMNS,\n" + " [Store].[Store Name].MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Drill Down More Than One Level Deep, or Skip Levels When * Drilling Down?</b> * * <p>Drilling down is an essential ability for most OLAP products, and * Analysis Services is no exception. Several functions exist that support * drilling up and down the hierarchy of dimensions within a cube. * Typically, drilling up and down the hierarchy is done one level at a * time; think of this functionality as a zoom feature for OLAP data. * * <p>There are times, though, when the need to drill down more than one * level at the same time, or even skip levels when displaying information * about multiple levels, exists for a business scenario. * * <p>For example, you would like to show report results from a query of * the Sales cube in the FoodMart 2000 sample database showing sales totals * for individual cities and the subtotals for each country, as shown in the * following table. * * <p>The Customers dimension, however, has Country, State Province, and * City levels. In order to show the above report, you would have to show * the Country level and then drill down two levels to show the City * level, skipping the State Province level entirely. * * <p>However, the MDX ToggleDrillState and DrillDownMember functions * provide drill down functionality only one level below a specified set. To * drill down more than one level below a specified set, you need to use a * combination of MDX functions, including Descendants, Generate, and * Except. This technique essentially constructs a large set that includes * all levels between both upper and lower desired levels, then uses a * smaller set representing the undesired level or levels to remove the * appropriate members from the larger set. * * <p>The MDX Descendants function is used to construct a set consisting of * the descendants of each member in the Customers dimension. The * descendants are determined using the MDX Descendants function, with the * descendants of the City level and the level above, the State Province * level, for each member of the Customers dimension being added to the * set. * * <p>The MDX Generate function now creates a set consisting of all members * at the Country level as well as the members of the set generated by the * MDX Descendants function. Then, the MDX Except function is used to * exclude all members at the State Province level, so the returned set * contains members at the Country and City levels. * * <p>Note, however, that the previous MDX query will still order the * members according to their hierarchy. Although the returned set contains * members at the Country and City levels, the Country, State Province, * and City levels determine the order of the members. */ public void _testDrillingDownMoreThanOneLevel() { assertQueryReturns( // todo: implement "GENERATE" "SELECT {[Measures].[Unit Sales]} ON COLUMNS,\n" + " EXCEPT(GENERATE([Customers].[Country].MEMBERS,\n" + " {DESCENDANTS([Customers].CURRENTMEMBER, [Customers].[City], SELF_AND_BEFORE)}),\n" + " {[Customers].[State Province].MEMBERS}) ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Do I Get the Topmost Members of a Level Broken Out by an Ancestor * Level?</b> * * <p>This type of MDX query is common when only the facts for the lowest * level of a dimension within a cube are needed, but information about * other levels within the same dimension may also be required to satisfy a * specific business scenario. * * <p>For example, a report that shows the unit sales for the store with * the highest unit sales from each country is needed for marketing * purposes. The following table provides an example of this report, run * against the Sales cube in the FoodMart 2000 sample database. * * <p>This looks simple enough, but the Country Name column provides * unexpected difficulty. The values for the Store Country column are taken * from the Store Country level of the Store dimension, so the Store * Country column is constructed as a calculated member as part of the MDX * query, using the MDX Ancestor and Name functions to return the country * names for each store. * * <p>A combination of the MDX Generate, TopCount, and Descendants * functions are used to create a set containing the top stores in unit * sales for each country. */ public void _testTopmost() { assertQueryReturns( // todo: implement "GENERATE" "WITH MEMBER Measures.[Country Name] AS \n" + " 'Ancestor(Store.CurrentMember, [Store Country]).Name'\n" + "SELECT {Measures.[Country Name], Measures.[Unit Sales]} ON COLUMNS,\n" + " GENERATE([Store Country].MEMBERS, \n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", ""); } /** * <p>The MDX Descendants function is used to construct a set consisting of * only those members at the Store Name level in the Store dimension. Then, * the MDX TopCount function is used to return only the topmost store based * on the Unit Sales measure. The MDX Generate function then constructs a * set based on the topmost stores, following the hierarchy of the Store * dimension. * * <p>Alternate techniques, such as using the MDX Crossjoin function, may * not provide the desired results because non-related joins can occur. * Since the Store Country and Store Name levels are within the same * dimension, they cannot be cross-joined. Another dimension that provides * the same regional hierarchy structure, such as the Customers dimension, * can be employed with the Crossjoin function. But, using this technique * can cause non-related joins and return unexpected results. * * <p>For example, the following MDX query uses the Crossjoin function to * attempt to return the same desired results. * * <p>However, some unexpected surprises occur because the topmost member * in the Store dimension is cross-joined with all of the children of the * Customers dimension, as shown in the following table. * * <p>In this instance, the use of a calculated member to provide store * country names is easier to understand and debug than attempting to * cross-join across unrelated members */ public void testTopmost2() { assertQueryReturns( "SELECT {Measures.[Unit Sales]} ON COLUMNS,\n" + " CROSSJOIN(Customers.CHILDREN,\n" + " TOPCOUNT(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]),\n" + " 1, [Measures].[Unit Sales])) ON ROWS\n" + "FROM Sales", fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Customers].[All Customers].[Canada], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[Mexico], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Customers].[All Customers].[USA], [Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: 41,580\n")); } /** * <b>How Can I Rank or Reorder Members?</b> * * <p>One of the issues commonly encountered in business scenarios is the * need to rank the members of a dimension according to their corresponding * measure values. The Order MDX function allows you to order a set based on * a string or numeric expression evaluated against the members of a set. * Combined with other MDX functions, the Order function can support * several different types of ranking. * * <p>For example, the Sales cube in the FoodMart 2000 database can be used * to show unit sales for each store. However, the business scenario * requires a report that ranks the stores from highest to lowest unit * sales, individually, of nonconsumable products. * * <p>Because of the requirement that stores be sorted individually, the * hierarchy must be broken (in other words, ignored) for the purpose of * ranking the stores. The Order function is capable of sorting within the * hierarchy, based on the topmost level represented in the set to be * sorted, or, by breaking the hierarchy, sorting all of the members of the * set as if they existed on the same level, with the same parent. * * <p>The following MDX query illustrates the use of the Order function to * rank the members according to unit sales. */ public void testRank() { assertQueryReturns( "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " ORDER([Store].[Store Name].MEMBERS, (Measures.[Unit Sales]), BDESC) ON ROWS\n" + "FROM Sales\n" + "WHERE [Product].[Non-Consumable]", fold("Axis "{[Product].[All Products].[Non-Consumable]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Store].[All Stores].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[All Stores].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[All Stores].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[All Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[All Stores].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[All Stores].[USA].[WA].[Yakima].[Store 23]}\n" + "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[All Stores].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[All Stores].[Canada].[BC].[Vancouver].[Store 19]}\n" + "{[Store].[All Stores].[Canada].[BC].[Victoria].[Store 20]}\n" + "{[Store].[All Stores].[Mexico].[DF].[Mexico City].[Store 9]}\n" + "{[Store].[All Stores].[Mexico].[DF].[San Andres].[Store 21]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz].[Orizaba].[Store 10]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan].[Merida].[Store 8]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 12]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas].[Hidalgo].[Store 18]}\n" + "{[Store].[All Stores].[USA].[CA].[Alameda].[HQ]}\n" + "Row #0: 7,940\n" + "Row #1: 6,712\n" + "Row #2: 5,076\n" + "Row #3: 4,947\n" + "Row #4: 4,706\n" + "Row #5: 4,639\n" + "Row #6: 4,479\n" + "Row #7: 4,428\n" + "Row #8: 3,950\n" + "Row #9: 2,140\n" + "Row #10: 442\n" + "Row #11: 390\n" + "Row #12: 387\n" + "Row #13: \n" + "Row #14: \n" + "Row #15: \n" + "Row #16: \n" + "Row #17: \n" + "Row #18: \n" + "Row #19: \n" + "Row #20: \n" + "Row #21: \n" + "Row #22: \n" + "Row #23: \n" + "Row #24: \n")); } /** * <b>How Can I Use Different Calculations for Different Levels in a * Dimension?</b> * * <p>This type of MDX query frequently occurs when different aggregations * are needed at different levels in a dimension. One easy way to support * such functionality is through the use of a calculated measure, created as * part of the query, which uses the MDX Descendants function in conjunction * with one of the MDX aggregation functions to provide results. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * supplies the [Units Ordered] measure, aggregated through the Sum * function. But, you would also like to see the average number of units * ordered per store. The following table demonstrates the desired results. * * <p>By using the following MDX query, the desired results can be * achieved. The calculated measure, [Average Units Ordered], supplies the * average number of ordered units per store by using the Avg, * CurrentMember, and Descendants MDX functions. */ public void testDifferentCalculationsForDifferentLevels() { assertQueryReturns( "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])',\n" + " FORMAT_STRING='#.00'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Store].[Store State].MEMBERS ON ROWS\n" + "FROM Warehouse", fold("Axis "{}\n" + "Axis "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis "{[Store].[All Stores].[Canada].[BC]}\n" + "{[Store].[All Stores].[Mexico].[DF]}\n" + "{[Store].[All Stores].[Mexico].[Guerrero]}\n" + "{[Store].[All Stores].[Mexico].[Jalisco]}\n" + "{[Store].[All Stores].[Mexico].[Veracruz]}\n" + "{[Store].[All Stores].[Mexico].[Yucatan]}\n" + "{[Store].[All Stores].[Mexico].[Zacatecas]}\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR]}\n" + "{[Store].[All Stores].[USA].[WA]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: \n" + "Row #1: \n" + "Row #2: \n" + "Row #2: \n" + "Row #3: \n" + "Row #3: \n" + "Row #4: \n" + "Row #4: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: \n" + "Row #6: \n" + "Row #7: 66307.0\n" + "Row #7: 16576.75\n" + "Row #8: 44906.0\n" + "Row #8: 22453.00\n" + "Row #9: 116025.0\n" + "Row #9: 16575.00\n")); } /** * <p>This calculated measure is more powerful than it seems; if, for * example, you then want to see the average number of units ordered for * beer products in all of the stores in the California area, the following * MDX query can be executed with the same calculated measure. */ public void testDifferentCalculations2() { assertQueryReturns( // todo: "[Store].[USA].[CA]" should be "[Store].CA", // "[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer]" should be "[Product].[Beer]" "WITH MEMBER Measures.[Average Units Ordered] AS\n" + " 'AVG(DESCENDANTS([Store].CURRENTMEMBER, [Store].[Store Name]), [Measures].[Units Ordered])'\n" + "SELECT {[Measures].[Units ordered], Measures.[Average Units Ordered]} ON COLUMNS,\n" + " [Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].CHILDREN ON ROWS\n" + "FROM Warehouse\n" + "WHERE [Store].[USA].[CA]", fold("Axis "{[Store].[All Stores].[USA].[CA]}\n" + "Axis "{[Measures].[Units Ordered]}\n" + "{[Measures].[Average Units Ordered]}\n" + "Axis "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Good]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Pearl]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Top Measure]}\n" + "{[Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Walrus]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #1: 151.0\n" + "Row #1: 75.5\n" + "Row #2: 95.0\n" + "Row #2: 95.0\n" + "Row #3: \n" + "Row #3: \n" + "Row #4: 211.0\n" + "Row #4: 105.5\n")); } /** * <b>How Can I Use Different Calculations for Different Dimensions?</b> * * <p>Each measure in a cube uses the same aggregation function across all * dimensions. However, there are times where a different aggregation * function may be needed to represent a measure for reporting purposes. Two * basic cases involve aggregating a single dimension using a different * aggregation function than the one used for other dimensions.<ul> * * <li>Aggregating minimums, maximums, or averages along a time dimension</li> * * <li>Aggregating opening and closing period values along a time * dimension</li></ul> * * <p>The first case involves some knowledge of the behavior of the time * dimension specified in the cube. For instance, to create a calculated * measure that contains the average, along a time dimension, of measures * aggregated as sums along other dimensions, the average of the aggregated * measures must be taken over the set of averaging time periods, * constructed through the use of the Descendants MDX function. Minimum and * maximum values are more easily calculated through the use of the Min and * Max MDX functions, also combined with the Descendants function. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show the average number of units shipped, by product, to * each store. Information on units shipped is added on a monthly basis, so * the aggregated measure [Units Shipped] is divided by the count of * descendants, at the Month level, of the current member in the Time * dimension. This calculation provides a measure representing the average * number of units shipped per month, as demonstrated in the following MDX * query. */ public void _testDifferentCalculationsForDifferentDimensions() { assertQueryReturns( // todo: implement "NONEMPTYCROSSJOIN" "WITH MEMBER [Measures].[Avg Units Shipped] AS\n" + " '[Measures].[Units Shipped] / \n" + " COUNT(DESCENDANTS([Time].CURRENTMEMBER, [Time].[Month], SELF))'\n" + "SELECT {Measures.[Units Shipped], Measures.[Avg Units Shipped]} ON COLUMNS,\n" + "NONEMPTYCROSSJOIN(Store.CA.Children, Product.MEMBERS) ON ROWS\n" + "FROM Warehouse", ""); } /** * <p>The second case is easier to resolve, because MDX provides the * OpeningPeriod and ClosingPeriod MDX functions specifically to support * opening and closing period values. * * <p>For example, the Warehouse cube in the FoodMart 2000 database * contains information on ordered and shipped inventory; from it, a report * is requested to show on-hand inventory at the end of every month. Because * the inventory on hand should equal ordered inventory minus shipped * inventory, the ClosingPeriod MDX function can be used to create a * calculated measure to supply the value of inventory on hand, as * demonstrated in the following MDX query. */ public void _testDifferentCalculationsForDifferentDimensions2() { assertQueryReturns( "WITH MEMBER Measures.[Closing Balance] AS\n" + " '([Measures].[Units Ordered], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER)) -\n" + " ([Measures].[Units Shipped], \n" + " CLOSINGPERIOD([Time].[Month], [Time].CURRENTMEMBER))'\n" + "SELECT {[Measures].[Closing Balance]} ON COLUMNS,\n" + " Product.MEMBERS ON ROWS\n" + "FROM Warehouse", ""); } /** * <b>How Can I Use Date Ranges in MDX?</b> * * <p>Date ranges are a frequently encountered problem. Business questions * use ranges of dates, but OLAP objects provide aggregated information in * date levels. * * <p>Using the technique described here, you can establish date ranges in * MDX queries at the level of granularity provided by a time dimension. * Date ranges cannot be established below the granularity of the dimension * without additional information. For example, if the lowest level of a * time dimension represents months, you will not be able to establish a * two-week date range without other information. Member properties can be * added to supply specific dates for members; using such member properties, * you can take advantage of the date and time functions provided by VBA and * Excel external function libraries to establish date ranges. * * <p>The easiest way to specify a static date range is by using the colon * (:) operator. This operator creates a naturally ordered set, using the * members specified on either side of the operator as the endpoints for the * ordered set. For example, to specify the first six months of 1998 from * the Time dimension in FoodMart 2000, the MDX syntax would resemble: * * <blockquote><pre>[Time].[1998].[1]:[Time].[1998].[6]</pre></blockquote> * * <p>For example, the Sales cube uses a time dimension that supports Year, * Quarter, and Month levels. To add a six-month and nine-month total, two * calculated members are created in the following MDX query. */ public void _testDateRange() { assertQueryReturns( // todo: implement "AddCalculatedMembers" "WITH MEMBER [Time].[1997].[Six Month] AS\n" + " 'SUM([Time].[1]:[Time].[6])'\n" + "MEMBER [Time].[1997].[Nine Month] AS\n" + " 'SUM([Time].[1]:[Time].[9])'\n" + "SELECT AddCalculatedMembers([Time].[1997].Children) ON COLUMNS,\n" + " [Product].Children ON ROWS\n" + "FROM Sales", ""); } /** * <b>How Can I Use Rolling Date Ranges in MDX?</b> * * <p>There are several techniques that can be used in MDX to support * rolling date ranges. All of these techniques tend to fall into two * groups. The first group involves the use of relative hierarchical * functions to construct named sets or calculated members, and the second * group involves the use of absolute date functions from external function * libraries to construct named sets or calculated members. Both groups are * applicable in different business scenarios. * * <p>In the first group of techniques, typically a named set is * constructed which contains a number of periods from a time dimension. For * example, the following table illustrates a 12-month rolling period, in * which the figures for unit sales of the previous 12 months are shown. * * <p>The following MDX query accomplishes this by using a number of MDX * functions, including LastPeriods, Tail, Filter, Members, and Item, to * construct a named set containing only those members across all other * dimensions that share data with the time dimension at the Month level. * The example assumes that there is at least one measure, such as [Unit * Sales], with a value greater than zero in the current period. The Filter * function creates a set of months with unit sales greater than zero, while * the Tail function returns the last month in this set, the current month. * The LastPeriods function, finally, is then used to retrieve the last 12 * periods at this level, including the current period. */ public void _testRolling() { assertQueryReturns( fold("WITH SET Rolling12 AS\n" + " 'LASTPERIODS(12, TAIL(FILTER([Time].[Month].MEMBERS, \n" + " ([Customers].[All Customers], \n" + " [Education Level].[All Education Level],\n" + " [Gender].[All Gender],\n" + " [Marital Status].[All Marital Status],\n" + " [Product].[All Products], \n" + " [Promotion Media].[All Media],\n" + " [Promotions].[All Promotions],\n" + " [Store].[All Stores],\n" + " [Store Size in SQFT].[All Store Size in SQFT],\n" + " [Store Type].[All Store Type],\n" + " [Yearly Income].[All Yearly Income],\n" + " Measures.[Unit Sales]) >0),\n" + " 1).ITEM(0).ITEM(0))'\n" + "SELECT {[Measures].[Unit Sales]} ON COLUMNS, \n" + " Rolling12 ON ROWS\n" + "FROM Sales"), ""); } /** * <b>How Can I Use Different Calculations for Different Time Periods?</b> * * <p>A few techniques can be used, depending on the structure of the cube * being queried, to support different calculations for members depending * on the time period. The following example includes the MDX IIf function, * and is easy to use but difficult to maintain. This example works well for * ad hoc queries, but is not the ideal technique for client applications in * a production environment. * * <p>For example, the following table illustrates a standard and dynamic * forecast of warehouse sales, from the Warehouse cube in the FoodMart 2000 * database, for drink products. The standard forecast is double the * warehouse sales of the previous year, while the dynamic forecast varies * from month to month -- the forecast for January is 120 percent of previous * sales, while the forecast for July is 260 percent of previous sales. * * <p>The most flexible way of handling this type of report is the use of * nested MDX IIf functions to return a multiplier to be used on the members * of the Products dimension, at the Drinks level. The following MDX query * demonstrates this technique. */ public void testDifferentCalcsForDifferentTimePeriods() { assertQueryReturns( // note: "[Product].[Drink Forecast - Standard]" was "[Drink Forecast - Standard]" "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " IIF([Time].CurrentMember.Name = \"1\", 1.2,\n" + " IIF([Time].CurrentMember.Name = \"2\", 1.3,\n" + " IIF([Time].CurrentMember.Name = \"3\", 1.4,\n" + " IIF([Time].CurrentMember.Name = \"4\", 1.6,\n" + " IIF([Time].CurrentMember.Name = \"5\", 2.1,\n" + " IIF([Time].CurrentMember.Name = \"6\", 2.4,\n" + " IIF([Time].CurrentMember.Name = \"7\", 2.6,\n" + " IIF([Time].CurrentMember.Name = \"8\", 2.3,\n" + " IIF([Time].CurrentMember.Name = \"9\", 1.9,\n" + " IIF([Time].CurrentMember.Name = \"10\", 1.5,\n" + " IIF([Time].CurrentMember.Name = \"11\", 1.4,\n" + " IIF([Time].CurrentMember.Name = \"12\", 1.2, 1.0))))))))))))'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Product].[Drink Forecast - Standard], [Product].[Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", fold("Axis "{}\n" + "Axis "{[Time].[1997].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "{[Time].[1997].[Q2].[6]}\n" + "{[Time].[1997].[Q3].[7]}\n" + "{[Time].[1997].[Q3].[8]}\n" + "{[Time].[1997].[Q3].[9]}\n" + "{[Time].[1997].[Q4].[10]}\n" + "{[Time].[1997].[Q4].[11]}\n" + "{[Time].[1997].[Q4].[12]}\n" + "Axis "{[Product].[All Products].[Drink]}\n" + "{[Product].[All Products].[Food]}\n" + "{[Product].[All Products].[Non-Consumable]}\n" + "{[Product].[Drink Forecast - Standard]}\n" + "{[Product].[Drink Forecast - Dynamic]}\n" + "Row #0: 881.847\n" + "Row #0: 579.051\n" + "Row #0: 476.292\n" + "Row #0: 618.722\n" + "Row #0: 778.886\n" + "Row #0: 636.935\n" + "Row #0: 937.842\n" + "Row #0: 767.332\n" + "Row #0: 920.707\n" + "Row #0: 1,007.764\n" + "Row #0: 820.808\n" + "Row #0: 792.167\n" + "Row #1: 8,383.446\n" + "Row #1: 4,851.406\n" + "Row #1: 5,353.188\n" + "Row #1: 6,061.829\n" + "Row #1: 6,039.282\n" + "Row #1: 5,259.242\n" + "Row #1: 6,902.01\n" + "Row #1: 5,790.772\n" + "Row #1: 8,167.053\n" + "Row #1: 6,188.732\n" + "Row #1: 5,344.845\n" + "Row #1: 5,025.744\n" + "Row #2: 2,040.396\n" + "Row #2: 1,269.816\n" + "Row #2: 1,460.686\n" + "Row #2: 1,696.757\n" + "Row #2: 1,397.035\n" + "Row #2: 1,578.136\n" + "Row #2: 1,671.046\n" + "Row #2: 1,609.447\n" + "Row #2: 2,059.617\n" + "Row #2: 1,617.493\n" + "Row #2: 1,909.713\n" + "Row #2: 1,382.364\n" + "Row #3: 1,763.693\n" + "Row #3: 1,158.102\n" + "Row #3: 952.584\n" + "Row #3: 1,237.444\n" + "Row #3: 1,557.773\n" + "Row #3: 1,273.87\n" + "Row #3: 1,875.685\n" + "Row #3: 1,534.665\n" + "Row #3: 1,841.414\n" + "Row #3: 2,015.528\n" + "Row #3: 1,641.615\n" + "Row #3: 1,584.334\n" + "Row #4: 1,058.216\n" + "Row #4: 752.766\n" + "Row #4: 666.809\n" + "Row #4: 989.955\n" + "Row #4: 1,635.661\n" + "Row #4: 1,528.644\n" + "Row #4: 2,438.39\n" + "Row #4: 1,764.865\n" + "Row #4: 1,749.343\n" + "Row #4: 1,511.646\n" + "Row #4: 1,149.13\n" + "Row #4: 950.601\n")); } /** * <p>Other techniques, such as the addition of member properties to the * Time or Product dimensions to support such calculations, are not as * flexible but are much more efficient. The primary drawback to using such * techniques is that the calculations are not easily altered for * speculative analysis purposes. For client applications, however, where * the calculations are static or slowly changing, using a member property * is an excellent way of supplying such functionality to clients while * keeping maintenance of calculation variables at the server level. The * same MDX query, for example, could be rewritten to use a member property * named [Dynamic Forecast Multiplier] as shown in the following MDX query. */ public void _testDc4dtp2() { assertQueryReturns( "WITH MEMBER [Product].[Drink Forecast - Standard] AS\n" + " '[Product].[All Products].[Drink] * 2'\n" + "MEMBER [Product].[Drink Forecast - Dynamic] AS \n" + " '[Product].[All Products].[Drink] * \n" + " [Time].CURRENTMEMBER.PROPERTIES(\"Dynamic Forecast Multiplier\")'\n" + "SELECT DESCENDANTS(Time.[1997], [Month], SELF) ON COLUMNS, \n" + " {[Product].CHILDREN, [Drink Forecast - Standard], [Drink Forecast - Dynamic]} ON ROWS\n" + "FROM Warehouse", ""); } public void _testWarehouseProfit() { assertQueryReturns( "select \n" + "{[Measures].[Warehouse Cost], [Measures].[Warehouse Sales], [Measures].[Warehouse Profit]}\n" + " ON COLUMNS from [Warehouse]", ""); } /** * <b>How Can I Compare Time Periods in MDX?</b> * * <p>To answer such a common business question, MDX provides a number of * functions specifically designed to navigate and aggregate information * across time periods. For example, year-to-date (YTD) totals are directly * supported through the YTD function in MDX. In combination with the MDX * ParallelPeriod function, you can create calculated members to support * direct comparison of totals across time periods. * * <p>For example, the following table represents a comparison of YTD unit * sales between 1997 and 1998, run against the Sales cube in the FoodMart * 2000 database. * * <p>The following MDX query uses three calculated members to illustrate * how to use the YTD and ParallelPeriod functions in combination to compare * time periods. */ public void _testYtdGrowth() { assertQueryReturns( // todo: implement "ParallelPeriod" "WITH MEMBER [Measures].[YTD Unit Sales] AS\n" + " 'COALESCEEMPTY(SUM(YTD(), [Measures].[Unit Sales]), 0)'\n" + "MEMBER [Measures].[Previous YTD Unit Sales] AS\n" + " '(Measures.[YTD Unit Sales], PARALLELPERIOD([Time].[Year]))'\n" + "MEMBER [Measures].[YTD Growth] AS\n" + " '[Measures].[YTD Unit Sales] - ([Measures].[Previous YTD Unit Sales])'\n" + "SELECT {[Time].[1998]} ON COLUMNS,\n" + " {[Measures].[YTD Unit Sales], [Measures].[Previous YTD Unit Sales], [Measures].[YTD Growth]} ON ROWS\n" + "FROM Sales ", ""); } /* * takes quite long */ public void dont_testParallelMutliple() { for (int i = 0; i < 5; i++) { runParallelQueries(1, 1, false); runParallelQueries(3, 2, false); runParallelQueries(4, 6, true); runParallelQueries(6, 10, false); } } public void dont_testParallelNot() { runParallelQueries(1, 1, false); } public void dont_testParallelSomewhat() { runParallelQueries(3, 2, false); } public void dont_testParallelFlushCache() { runParallelQueries(4, 6, true); } public void dont_testParallelVery() { runParallelQueries(6, 10, false); } private void runParallelQueries(final int threadCount, final int iterationCount, final boolean flush) { long timeoutMs = threadCount * iterationCount * 600 * 1000; // 10 minute per query final int[] executeCount = new int[] {0}; final QueryAndResult[] queries = new QueryAndResult[sampleQueries.length + taglibQueries.length]; System.arraycopy(sampleQueries, 0, queries, 0, sampleQueries.length); System.arraycopy(taglibQueries, 0, queries, sampleQueries.length, taglibQueries.length); TestCaseForker threaded = new TestCaseForker( this, timeoutMs, threadCount, new ChooseRunnable() { public void run(int i) { for (int j = 0; j < iterationCount; j++) { int queryIndex = (i * 2 + j) % queries.length; try { QueryAndResult query = queries[queryIndex]; assertQueryReturns(query.query, query.result); if (flush && i == 0) { CachePool.instance().flush(); } synchronized (executeCount) { executeCount[0]++; } } catch (Throwable e) { e.printStackTrace(); throw Util.newInternal( e, "Thread " failed while executing query queryIndex); } } } }); threaded.run(); assertEquals("number of executions", threadCount * iterationCount, executeCount[0]); } /** * Makes sure that the expression <code> * * [Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All Products]) * * </code> depends on the current member of the Product dimension, although * [Product].[All Products] is referenced from the expression. */ public void testDependsOn() { assertQueryReturns( "with member [Customers].[my] as \n" + " 'Aggregate(Filter([Customers].[City].Members, (([Measures].[Unit Sales] / ([Measures].[Unit Sales], [Product].[All Products])) > 0.1)))' \n" + "select \n" + " {[Measures].[Unit Sales]} ON columns, \n" + " {[Product].[All Products].[Food].[Deli], [Product].[All Products].[Food].[Frozen Foods]} ON rows \n" + "from [Sales] \n" + "where ([Customers].[my], [Time].[1997])\n", fold("Axis "{[Customers].[my], [Time].[1997]}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Product].[All Products].[Food].[Deli]}\n" + "{[Product].[All Products].[Food].[Frozen Foods]}\n" + "Row #0: 13\n" + "Row #1: 15,111\n")); } /** * This resulted in {@link OutOfMemoryError} when the * BatchingCellReader did not know the values for the tuples that * were used in filters. */ public void testFilteredCrossJoin() { CachePool.instance().flush(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " Filter([Customers].[Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0)),\n" + " Filter([Product].[Product Name].Members,\n" + " (([Measures].[Store Sales],\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]) > 5.0))\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(12, a.positions.length); } /** * This resulted in an OutOfMemoryError */ public void testNonEmptyCrossJoin() { CachePool.instance().flush(); Result result = executeQuery( "select {[Measures].[Store Sales]} on columns,\n" + " NON EMPTY Crossjoin(\n" + " [Customers].[Name].Members,\n" + " [Product].[Product Name].Members\n" + " ) ON rows\n" + "from [Sales]\n" + "where (\n" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14],\n" + " [Time].[1997].[Q1].[1]\n" + ")\n"); // ok if no OutOfMemoryError occurs Axis a = result.getAxes()[1]; assertEquals(67, a.positions.length); } public void testNonEmptyNonEmptyCrossJoin1() { CachePool.instance().flush(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(306, a.positions.length); } public void testNonEmptyNonEmptyCrossJoin2() { CachePool.instance().flush(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(10, a.positions.length); } public void testNonEmptyNonEmptyCrossJoin3() { CachePool.instance().flush(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty CrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.positions.length); } public void testNonEmptyNonEmptyCrossJoin4() { CachePool.instance().flush(); Result result = executeQuery( "select {[Education Level].[All Education Levels].[Graduate Degree]} on columns,\n" + " Non Empty NonEmptyCrossJoin(\n" + " {[Store Type].[Store Type].members},\n" + " {[Promotions].[Promotion Name].members})\n" + " on rows\n" + "from Sales\n" + "where ([Customers].[All Customers].[USA].[WA].[Anacortes])\n"); Axis a = result.getAxes()[1]; assertEquals(1, a.positions.length); } public void testHierDifferentKeyClass() { Result result = executeQuery("with member [Time].[1997].[Q1].[xxx] as\n" + "'Aggregate({[Time].[1997].[Q1].[1], [Time].[1997].[Q1].[2]})'\n" + "select {[Measures].[Unit Sales], [Measures].[Store Cost],\n" + "[Measures].[Store Sales]} ON columns,\n" + "Hierarchize(Union(Union({[Time].[1997], [Time].[1998],\n" + "[Time].[1997].[Q1].[xxx]}, [Time].[1997].Children),\n" + "[Time].[1997].[Q1].Children)) ON rows from [Sales]"); Axis a = result.getAxes()[1]; assertEquals(10, a.positions.length); } /** * Bug #1005995 - many totals of various dimensions */ public void testOverlappingCalculatedMembers() { String query = "WITH MEMBER [Store].[Total] AS 'SUM([Store].[Store Country].MEMBERS)' " + "MEMBER [Store Type].[Total] AS 'SUM([Store Type].[Store Type].MEMBERS)' " + "MEMBER [Gender].[Total] AS 'SUM([Gender].[Gender].MEMBERS)' " + "MEMBER [Measures].[x] AS '[Measures].[Store Sales]' " + "SELECT {[Measures].[x]} ON COLUMNS , " + "{ ([Store].[Total], [Store Type].[Total], [Gender].[Total]) } ON ROWS " + "FROM Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis #1:\n" + "{[Measures].[x]}\n" + "Axis "{[Store].[Total], [Store Type].[Total], [Gender].[Total]}\n" + "Row #0: 565,238.13\n"); assertQueryReturns(query, desiredResult); } /** * the following query raised a classcast exception because * an empty property evaluated as "NullMember" * note: Store "HQ" does not have a "Store Manager" */ public void testEmptyProperty() { String query = "select {[Measures].[Unit Sales]} on columns, " + "filter([Store].[Store Name].members," + "[Store].currentmember.properties(\"Store Manager\")=\"Smith\") on rows" + " from Sales"; String desiredResult = fold( "Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "Row #0: 2,237\n"); assertQueryReturns(query, desiredResult); } /** * This test modifies the Sales cube to contain both the regular usage * of the [Store] shared dimension, and another usage called [Other Store] * which is connected to the [Unit Sales] column */ public void _testCubeWhichUsesSameSharedDimTwice() { RolapConnection conn = (RolapConnection) getConnection(); Schema schema = conn.getSchema(); final Cube salesCube = schema.lookupCube("Sales", true); // Create a second usage of the "Store" shared dimension called "Other // Store". Attach it to the "unit_sales" column (which has values [1, // 6] whereas store has values [1, 24]. schema.createDimension( salesCube, "<DimensionUsage name=\"Other Store\" source=\"Store\" foreignKey=\"unit_sales\" />"); Axis axis = getTestContext().executeAxis("[Other Store].members"); assertEquals(63, axis.positions.length); axis = getTestContext().executeAxis("[Store].members"); assertEquals(63, axis.positions.length); final String q1 = fold( "select {[Measures].[Unit Sales]} on columns,\n" + " NON EMPTY {[Other Store].members} on rows\n" + "from [Sales]"); assertQueryReturns(q1, fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Other Store].[All Other Stores]}\n" + "{[Other Store].[All Other Stores].[Mexico]}\n" + "{[Other Store].[All Other Stores].[USA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas]}\n" + "{[Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Other Store].[All Other Stores].[USA].[WA]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Guerrero].[Acapulco].[Store 1]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Jalisco].[Guadalajara].[Store 5]}\n" + "{[Other Store].[All Other Stores].[Mexico].[Zacatecas].[Camacho].[Store 4]}\n" + "{[Other Store].[All Other Stores].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Other Store].[All Other Stores].[USA].[WA].[Bremerton].[Store 3]}\n" + "Row #0: 266,773\n" + "Row #1: 110,822\n" + "Row #2: 155,951\n" + "Row #3: 1,827\n" + "Row #4: 14,915\n" + "Row #5: 94,080\n" + "Row #6: 222\n" + "Row #7: 155,729\n" + "Row #8: 1,827\n" + "Row #9: 14,915\n" + "Row #10: 94,080\n" + "Row #11: 222\n" + "Row #12: 39,362\n" + "Row #13: 116,367\n" + "Row #14: 1,827\n" + "Row #15: 14,915\n" + "Row #16: 94,080\n" + "Row #17: 222\n" + "Row #18: 39,362\n" + "Row #19: 116,367\n")); final String q2 = fold( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin(\n" + " {[Store].[USA], [Store].[USA].[CA], [Store].[USA].[OR].[Portland]}, \n" + " {[Other Store].[USA], [Other Store].[USA].[CA], [Other Store].[USA].[OR].[Portland]}) on rows\n" + "from [Sales]"); assertQueryReturns(q2, fold("Axis "{}\n" + "Axis "{[Measures].[Unit Sales]}\n" + "Axis "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[CA], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[OR].[Portland], [Other Store].[All Other Stores].[USA].[OR].[Portland]}\n" + "Row #0: 155,951\n" + "Row #1: 222\n" + "Row #2: \n" + "Row #3: 43,730\n" + "Row #4: 66\n" + "Row #5: \n" + "Row #6: 15,134\n" + "Row #7: 24\n" + "Row #8: \n")); Result result = executeQuery(q2); final Cell cell = result.getCell(new int[] {0, 0}); String sql = cell.getDrillThroughSQL(false); // the following replacement is for databases in ANSI mode // using '"' to quote identifiers sql = sql.replace('"', '`'); String tableQualifier = "as "; //RolapConnection conn = (RolapConnection) getConnection(); String jdbc_url = conn.getConnectInfo().get("Jdbc"); if (jdbc_url.toLowerCase().indexOf("oracle") >= 0) { // " + tableQualifier + " tableQualifier = ""; } assertEquals("select `store`.`store_country` as `Store Country`," + " `time_by_day`.`the_year` as `Year`," + " `store_1`.`store_country` as `x0`," + " `sales_fact_1997`.`unit_sales` as `Unit Sales` " + "from `store` " + tableQualifier + "`store`," + " `sales_fact_1997` " + tableQualifier + "`sales_fact_1997`," + " `time_by_day` " + tableQualifier + "`time_by_day`," + " `store` " + tableQualifier + "`store_1` " + "where `sales_fact_1997`.`store_id` = `store`.`store_id`" + " and `store`.`store_country` = 'USA'" + " and `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`" + " and `time_by_day`.`the_year` = 1997" + " and `sales_fact_1997`.`unit_sales` = `store_1`.`store_id`" + " and `store_1`.`store_country` = 'USA'", sql); } public void testMemberVisibility() { Schema schema = getConnection().getSchema(); final Cube cube = schema.createCube( "<Cube name=\"Sales_MemberVis\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\" " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\" " <Measure name=\"Sales Count\" column=\"product_id\" aggregator=\"count\"\n" + " formatString=\" " <Measure name=\"Customer Count\" column=\"customer_id\"\n" + " aggregator=\"distinct count\" formatString=\" " <CalculatedMember\n" + " name=\"Profit\"\n" + " dimension=\"Measures\"\n" + " visible=\"false\"\n" + " formula=\"[Measures].[Store Sales]-[Measures].[Store Cost]\">\n" + " <CalculatedMemberProperty name=\"FORMAT_STRING\" value=\"$#,##0.00\"/>\n" + " </CalculatedMember>\n" + "</Cube>"); final SchemaReader scr = cube.getSchemaReader(null); Member member = scr.getMemberByUniqueName(new String[] {"Measures", "Unit Sales"}, true); Object visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); member = scr.getMemberByUniqueName(new String[] {"Measures", "Store Cost"}, true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.TRUE, visible); member = scr.getMemberByUniqueName(new String[] {"Measures", "Profit"}, true); visible = member.getPropertyValue(Property.VISIBLE.name); assertEquals(Boolean.FALSE, visible); } public void testAllMemberCaption() { RolapConnection conn = (RolapConnection) getConnection(); Schema schema = getConnection().getSchema(); final Cube salesCube = schema.lookupCube("Sales", true); schema.createDimension( salesCube, fold("<Dimension name=\"Gender3\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allMemberCaption=\"Frauen und Maenner\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); String mdx = "select {[Gender3].[All Gender]} on columns from Sales"; Result result = TestContext.instance().executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.positions[0]; Member allGender = pos0.members[0]; String caption = allGender.getCaption(); Assert.assertEquals(caption, "Frauen und Maenner"); } public void testAllLevelName() { RolapConnection conn = (RolapConnection) getConnection(); Schema schema = getConnection().getSchema(); final Cube salesCube = schema.lookupCube("Sales", true); schema.createDimension( salesCube, fold("<Dimension name=\"Gender4\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\"\n" + " allLevelName=\"GenderLevel\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); String mdx = "select {[Gender4].[All Gender]} on columns from Sales"; Result result = TestContext.instance().executeQuery(mdx); Axis axis0 = result.getAxes()[0]; Position pos0 = axis0.positions[0]; Member allGender = pos0.members[0]; String caption = allGender.getLevel().getName(); Assert.assertEquals(caption, "GenderLevel"); } /** * Bug 1250080 caused a dimension with no 'all' member to be constrained * twice. */ public void testDimWithoutAll() { Connection conn = getConnection(); Schema schema = getConnection().getSchema(); final Cube cube = schema.createCube( "<Cube name=\"Sales_DimWithoutAll\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <Dimension name=\"Product\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"product_id\" primaryKeyTable=\"product\">\n" + " <Join leftKey=\"product_class_id\" rightKey=\"product_class_id\">\n" + " <Table name=\"product\"/>\n" + " <Table name=\"product_class\"/>\n" + " </Join>\n" + " <Level name=\"Product Family\" table=\"product_class\" column=\"product_family\"\n" + " uniqueMembers=\"true\"/>\n" + " <Level name=\"Product Department\" table=\"product_class\" column=\"product_department\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Category\" table=\"product_class\" column=\"product_category\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Subcategory\" table=\"product_class\" column=\"product_subcategory\"\n" + " uniqueMembers=\"false\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n" + " uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\" "</Cube>"); // Create a test context which evaluates expressions against the // "Sales_DimWithoutAll" cube, not the "Sales" cube. TestContext testContext = new DelegatingTestContext(getTestContext()) { public String getDefaultCubeName() { return "Sales_DimWithoutAll"; } }; // the default member of the Gender dimension is the first member testContext.assertExprReturns("[Gender].CurrentMember.Name", "F"); testContext.assertExprReturns("[Product].CurrentMember.Name", "Drink"); // There is no all member. testContext.assertExprThrows("([Gender].[All Gender], [Measures].[Unit Sales])", "MDX object '[Gender].[All Gender]' not found in cube 'Sales_DimWithoutAll'"); testContext.assertExprThrows("([Gender].[All Genders], [Measures].[Unit Sales])", "MDX object '[Gender].[All Genders]' not found in cube 'Sales_DimWithoutAll'"); // evaluated in the default context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns("[Measures].[Unit Sales]", "12,202"); // evaluated in the same context: [Product].[Drink], [Gender].[F] testContext.assertExprReturns("([Gender].[F], [Measures].[Unit Sales])", "12,202"); // evaluated at in the context: [Product].[Drink], [Gender].[M] testContext.assertExprReturns("([Gender].[M], [Measures].[Unit Sales])", "12,395"); // evaluated at in the context: [Product].[Food].[Canned Foods], [Gender].[F] testContext.assertExprReturns("([Product].[Food].[Canned Foods], [Measures].[Unit Sales])", "9,407"); testContext.assertExprReturns("([Product].[Food].[Dairy], [Measures].[Unit Sales])", "6,513"); testContext.assertExprReturns("([Product].[Drink].[Dairy], [Measures].[Unit Sales])", "1,987"); } public void testSameDimOnTwoAxesFails() { assertThrows( fold("select {[Measures].[Unit Sales]} on columns,\n" + " {[Measures].[Store Sales]} on rows\n" + "from [Sales]"), "Dimension '[Measures]' appears in more than one independent axis"); // as part of a crossjoin assertThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Product].members}," + " {[Measures].[Store Sales]}) on rows\n" + "from [Sales]", "Dimension '[Measures]' appears in more than one independent axis"); // as part of a tuple assertThrows( fold("select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].CurrentMember)} on rows\n" + "from [Sales]"), "Dimension '[Product]' appears in more than one independent axis"); // clash between columns and slicer assertThrows( fold("select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Measures].[Store Sales])"), "Dimension '[Measures]' appears in more than one independent axis"); // within aggregate is OK executeQuery("with member [Measures].[West Coast Total] as " + " ' Aggregate({[Store].[USA].[CA], [Store].[USA].[OR], [Store].[USA].[WA]}) ' \n" + "select " + " {[Measures].[Store Sales], \n" + " [Measures].[Unit Sales]} on Columns,\n" + " CrossJoin(\n" + " {[Product].children},\n" + " {[Store].children}) on Rows\n" + "from [Sales]"); } public void _testSetArgToTupleFails() { assertThrows( "select CrossJoin(\n" + " {[Product].children},\n" + " {[Measures].[Unit Sales]}) on columns,\n" + " {([Product],\n" + " [Store].members)} on rows\n" + "from [Sales]", "Dimension '[Product]' appears in more than one independent axis"); } public void _badArgsToTupleFails() { // clash within slicer assertThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " {[Store].Members} on rows\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1], [Product], [Time].[1997].[Q2])", "Dimension '[Time]' more than once in same tuple"); // ditto assertThrows( "select {[Measures].[Unit Sales]} on columns,\n" + " CrossJoin({[Time].[1997].[Q1],\n" + " {[Product]},\n" + " {[Time].[1997].[Q2]}) on rows\n" + "from [Sales]", "Dimension '[Time]' more than once in same tuple"); } public void testNullMember() { assertQueryReturns( "SELECT \n" + "{[Measures].[Store Cost]} ON columns, \n" + "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]} ON rows \n" + "FROM [Sales] \n" + "WHERE [Time].[1997]", fold("Axis "{[Time].[1997]}\n" + "Axis "{[Measures].[Store Cost]}\n" + "Axis "{[Store Size in SQFT].[All Store Size in SQFTs].[#null]}\n" + "Row #0: 33,307.69\n")); } /** * Tests whether the agg mgr behaves correctly if a cell request causes * a column to be constrained multiple times. This happens if two levels * map to the same column via the same join-path. If the constraints are * inconsistent, no data will be returned. */ public void testMultipleConstraintsOnSameColumn() { TestContext testContext = new TestContext() { public Connection getConnection() { return super.getConnection(); } }; Connection conn = getConnection(); Schema schema = getConnection().getSchema(); final String cubeName = "Sales_withCities"; final Cube cube = schema.createCube( "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Dimension name=\"Cities\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Cities\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Customers\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Customers\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/>\n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Name\" column=\"fullname\" uniqueMembers=\"true\">\n" + " <Property name=\"Gender\" column=\"gender\"/>\n" + " <Property name=\"Marital Status\" column=\"marital_status\"/>\n" + " <Property name=\"Education\" column=\"education\"/>\n" + " <Property name=\"Yearly Income\" column=\"yearly_income\"/>\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\" visible=\"false\"/>\n" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\" "</Cube>"); try { // Note that USA, CA, Burbank, and Alma Son are consistent with the // constraint in the slicer, and therefore return a value, but other // members are inconsistent so return null. getTestContext().assertQueryReturns( fold( "select {\n" + " [Customers].[All Customers].[USA],\n" + " [Customers].[All Customers].[USA].[OR],\n" + " [Customers].[All Customers].[USA].[CA],\n" + " [Customers].[All Customers].[USA].[CA].[Altadena],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank],\n" + " [Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]} ON COLUMNS\n" + "from [" + cubeName + "] \n" + "where ([Cities].[All Cities].[Burbank], [Measures].[Store Sales])"), fold( "Axis "{[Cities].[All Cities].[Burbank], [Measures].[Store Sales]}\n" + "Axis "{[Customers].[All Customers].[USA]}\n" + "{[Customers].[All Customers].[USA].[OR]}\n" + "{[Customers].[All Customers].[USA].[CA]}\n" + "{[Customers].[All Customers].[USA].[CA].[Altadena]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank]}\n" + "{[Customers].[All Customers].[USA].[CA].[Burbank].[Alma Son]}\n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: \n" + "Row #0: 6,577.33\n" + "Row #0: 36.50\n")); } finally { schema.removeCube(cubeName); } } public void testOverrideDimension() { assertQueryReturns( fold( "with member [Gender].[test] as '\n" + " aggregate(\n" + " filter ( crossjoin( [Gender].[Gender].members, [Time].members), \n" + " [time].CurrentMember = [Time].[1997].[Q1] AND\n" + "[measures].[unit sales] > 50) )\n" + "'\n" + "select \n" + " { [time].[year].members } on 0,\n" + " { [gender].[test] }\n" + " on 1 \n" + "from [sales]"), fold( "Axis "{}\n" + "Axis "{[Time].[1997]}\n" + "{[Time].[1998]}\n" + "Axis "{[Gender].[test]}\n" + "Row #0: 66,291\n" + "Row #0: 66,291\n")); } public void testBadMeasure1() { Schema schema = getConnection().getSchema(); final String cubeName = "SalesWithBadMeasure"; Throwable throwable = null; try { schema.createCube( "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" aggregator=\"sum\"\n" + " formatString=\"Standard\"/>\n" + "</Cube>"); } catch (Throwable e) { throwable = e; } // neither a source column or source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); schema.removeCube(cubeName); } public void testBadMeasure2() { Schema schema = getConnection().getSchema(); final String cubeName = "SalesWithBadMeasure"; Throwable throwable = null; try { schema.createCube( "<Cube name=\"" + cubeName + "\">\n" + " <Table name=\"sales_fact_1997\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Bad Measure\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\">\n" + " <MeasureExpression>\n" + " <SQL dialect=\"generic\">\n" + " unit_sales\n" + " </SQL>\n" + " </MeasureExpression>\n" + " </Measure>\n" + "</Cube>"); } catch (Throwable e) { throwable = e; } // both a source column and source expression specified TestContext.checkThrowable( throwable, "must contain either a source column or a source expression, but not both"); schema.removeCube(cubeName); } public void testCancel() { // the cancel is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times String query = fold(new String[] { "WITH ", " MEMBER [Measures].[Sleepy] ", " AS 'SleepUdf([Measures].[Unit Sales])' ", "SELECT {[Measures].[Sleepy]} ON COLUMNS,", " {[Product].members} ON ROWS", "FROM [Sales]"}); executeAndCancel(query, 2000); } private void executeAndCancel(String queryString, int waitMillis) { final TestContext tc = new TestContext() { public synchronized Connection getFoodMartConnection( boolean fresh) { return getFoodMartConnection( FoodmartWithSleepUdf.class.getName()); } }; Connection connection = tc.getConnection(); final Query query = connection.parseQuery(queryString); if (waitMillis == 0) { // cancel immediately query.cancel(); } else { // Schedule timer to cancel after waitMillis Timer timer = new Timer(true); TimerTask task = new TimerTask() { public void run() { Thread thread = Thread.currentThread(); thread.setName("CancelThread"); try { query.cancel(); } catch (Exception ex) { Assert.fail( "Cancel request failed: " + ex.getMessage()); } } }; timer.schedule(task, waitMillis); } Throwable throwable = null; try { connection.execute(query); } catch (Throwable ex) { throwable = ex; } TestContext.checkThrowable(throwable, "canceled"); } public void testQueryTimeout() { // timeout is issued after 2 seconds so the test query needs to // run for at least that long; it will because the query references // a Udf that has a 1 ms sleep in it; and there are enough rows // in the result that the Udf should execute > 2000 times int origTimeout = MondrianProperties.instance().QueryTimeout.get(); MondrianProperties.instance().QueryTimeout.set(2); final TestContext tc = new TestContext() { public synchronized Connection getFoodMartConnection( boolean fresh) { return getFoodMartConnection( FoodmartWithSleepUdf.class.getName()); } }; Connection connection = tc.getConnection(); String query = fold(new String[] { "WITH ", " MEMBER [Measures].[Sleepy] ", " AS 'SleepUdf([Measures].[Unit Sales])' ", "SELECT {[Measures].[Sleepy]} ON COLUMNS,", " {[Product].members} ON ROWS", "FROM [Sales]"}); Throwable throwable = null; try { tc.executeQuery(query); } catch (Throwable ex) { throwable = ex; } TestContext.checkThrowable( throwable, "Query timeout of 2 seconds reached"); // reset the timeout back to the original value MondrianProperties.instance().QueryTimeout.set(origTimeout); } /** * Adds a UDF that has a sleep call into the Foodmart schema. Used * by tests that exercise query cancel/timeout. */ public static class FoodmartWithSleepUdf extends DecoratingSchemaProcessor { protected String filterSchema(String s) { return Util.replace( s, "</Schema>", "<UserDefinedFunction name=\"SleepUdf\" className=\"" + SleepUdf.class.getName() + "\"/>" + nl + "</Schema>"); } } /** * A simple user-defined function which adds one to its argument, but * sleeps 1 ms before doing so. */ public static class SleepUdf implements UserDefinedFunction { public String getName() { return "SleepUdf"; } public String getDescription() { return "Returns its argument plus one but sleeps 1 ms first"; } public Syntax getSyntax() { return Syntax.Function; } public Type getReturnType(Type[] parameterTypes) { return new NumericType(); } public Type[] getParameterTypes() { return new Type[] {new NumericType()}; } public Object execute(Evaluator evaluator, Argument[] arguments) { final Object argValue = arguments[0].evaluateScalar(evaluator); if (argValue instanceof Number) { try { Thread.sleep(1); } catch (Exception ex) { return null; } return new Double(((Number) argValue).doubleValue() + 1); } else { // Argument might be a RuntimeException indicating that // the cache does not yet have the required cell value. The // function will be called again when the cache is loaded. return null; } } public String[] getReservedWords() { return null; } } } // End BasicQueryTest.java
package de.lmu.ifi.dbs.elki.logging; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Facility for configuration of logging. * * @author Arthur Zimek */ public final class LoggingConfiguration { /** * General debug flag. */ public static boolean DEBUG = false; /** * Configuration file name */ private static final String CLIConffile = "logging-cli.properties"; /** * Configuration base */ private static final String confbase = LoggingConfiguration.class.getPackage().getName(); /** * Static instance of the configuration */ protected static LoggingConfiguration config = new LoggingConfiguration(); /** * Configure Java Logging API: {@link java.util.logging} */ private LoggingConfiguration() { LogManager logManager = LogManager.getLogManager(); LogLevel.assertLevelsLoaded(); Logger logger = Logger.getLogger(LoggingConfiguration.class.getName()); // Load logging configuration from resources. try { InputStream cfgdata = null; // try in the file system first File cfgfile = new File(confbase.replace('.', File.separatorChar) + File.separatorChar + CLIConffile); if(cfgfile.exists() && cfgfile.canRead()) { cfgdata = new FileInputStream(cfgfile.getAbsolutePath()); } else // otherwise, load from system resources { cfgdata = ClassLoader.getSystemResourceAsStream(confbase.replace('.', '/') + '/' + CLIConffile); } // Load logging configuration if(cfgdata != null) { logManager.readConfiguration(cfgdata); logger.info("Logging configuration read."); } else { logger.warning("No logging configuration found."); } } catch(Exception e) { logger.log(Level.SEVERE, "Failed to configure logging.", e); } loadConfigurationPrivate(confbase, CLIConffile); } /** * Load a configuration file. * * @param cfgfile */ private void loadConfigurationPrivate(final String pkg, final String name) { final Logger logger = Logger.getLogger(LoggingConfiguration.class.getName()); final String base = (pkg == null) ? "" : pkg; if (name == null) { logger.log(Level.SEVERE, "No configuration file name given."); return; } // extra config settings // try in the file system first File cfgfile = new File(base.replace('.', File.separatorChar) + File.separatorChar + name); Properties cfgprop = new Properties(); try { InputStream res = ClassLoader.getSystemResourceAsStream(base.replace('.', '/') + '/' + name); if (res != null) { cfgprop.load(res); } if(cfgfile.exists() && cfgfile.canRead()) { cfgprop.load(new FileInputStream(cfgfile.getAbsolutePath())); } } catch(Exception e) { logger.log(Level.SEVERE, "Failed to load logging properties from "+cfgfile.getAbsolutePath(), e); } DEBUG = Boolean.valueOf(cfgprop.getProperty("debug")); } /** * Reconfigure logging using a configuration file. * * @param pkg Package name, may be null * @param name File name, may not be null */ public static void loadConfiguration(final String pkg, final String name) { config.loadConfigurationPrivate(pkg, name); } /** * Assert that logging was configured. */ public static void assertConfigured() { // nothing happening here, just to ensure static construction was run. } }
package de.lmu.ifi.dbs.elki.result.textwriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import de.lmu.ifi.dbs.elki.data.Clustering; import de.lmu.ifi.dbs.elki.data.DatabaseObject; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroup; import de.lmu.ifi.dbs.elki.data.DatabaseObjectGroupCollection; import de.lmu.ifi.dbs.elki.data.HierarchicalClassLabel; import de.lmu.ifi.dbs.elki.data.SimpleClassLabel; import de.lmu.ifi.dbs.elki.data.cluster.Cluster; import de.lmu.ifi.dbs.elki.data.cluster.naming.NamingScheme; import de.lmu.ifi.dbs.elki.data.cluster.naming.SimpleEnumeratingScheme; import de.lmu.ifi.dbs.elki.data.model.Model; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.distance.Distance; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.normalization.Normalization; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.CollectionResult; import de.lmu.ifi.dbs.elki.result.IterableResult; import de.lmu.ifi.dbs.elki.result.MultiResult; import de.lmu.ifi.dbs.elki.result.OrderingResult; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultUtil; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterDatabaseObjectInline; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectComment; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectInline; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTextWriteable; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterTriple; import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterVector; import de.lmu.ifi.dbs.elki.utilities.HandlerList; import de.lmu.ifi.dbs.elki.utilities.UnableToComplyException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AttributeSettings; import de.lmu.ifi.dbs.elki.utilities.pairs.Pair; import de.lmu.ifi.dbs.elki.utilities.pairs.Triple; /** * Class to write a result to human-readable text output * * @author Erich Schubert * * @param <O> Object type */ @SuppressWarnings("unchecked") public class TextWriter<O extends DatabaseObject> { /** * Logger */ private static final Logging logger = Logging.getLogger(TextWriter.class); /** * Extension for txt-files. */ public static final String FILE_EXTENSION = ".txt"; /** * Hash map for supported classes in writer. */ public final static HandlerList<TextWriterWriterInterface<?>> writers = new HandlerList<TextWriterWriterInterface<?>>(); /** * Add some default handlers */ static { TextWriterObjectInline trivialwriter = new TextWriterObjectInline(); writers.insertHandler(Object.class, new TextWriterObjectComment()); writers.insertHandler(DatabaseObject.class, new TextWriterDatabaseObjectInline<DatabaseObject>()); // these object can be serialized inline with toString() writers.insertHandler(String.class, trivialwriter); writers.insertHandler(Double.class, trivialwriter); writers.insertHandler(Integer.class, trivialwriter); writers.insertHandler(BitSet.class, trivialwriter); writers.insertHandler(Vector.class, new TextWriterVector()); writers.insertHandler(Distance.class, trivialwriter); writers.insertHandler(SimpleClassLabel.class, trivialwriter); writers.insertHandler(HierarchicalClassLabel.class, trivialwriter); writers.insertHandler(Triple.class, new TextWriterTriple()); // Objects that have an own writeToText method. writers.insertHandler(TextWriteable.class, new TextWriterTextWriteable()); } /** * Normalization to use. */ private Normalization<O> normalization; /** * Writes a header providing information concerning the underlying database * and the specified parameter-settings. * * @param db to retrieve meta information from * @param out the print stream where to write * @param settings the settings to be written into the header */ protected void printSettings(Database<O> db, TextWriterStream out, List<AttributeSettings> settings) { out.commentPrintSeparator(); out.commentPrintLn("Settings and meta information:"); out.commentPrintLn("db size = " + db.size()); // noinspection EmptyCatchBlock try { int dimensionality = db.dimensionality(); out.commentPrintLn("db dimensionality = " + dimensionality); } catch(UnsupportedOperationException e) { // dimensionality is unsupported - do nothing } out.commentPrintLn(""); if(settings != null) { for(AttributeSettings setting : settings) { if(!setting.getSettings().isEmpty()) { out.commentPrintLn(setting.toString()); out.commentPrintLn(""); } } } out.commentPrintSeparator(); out.flush(); } /** * Stream output. * * @param db Database object * @param r Result class * @param streamOpener output stream manager * @throws UnableToComplyException * @throws IOException */ public void output(Database<O> db, Result r, StreamFactory streamOpener) throws UnableToComplyException, IOException { List<AnnotationResult<?>> ra = null; List<OrderingResult> ro = null; List<Clustering<? extends Model>> rc = null; List<IterableResult<?>> ri = null; Collection<DatabaseObjectGroup> groups = null; ra = ResultUtil.getAnnotationResults(r); ro = ResultUtil.getOrderingResults(r); rc = ResultUtil.getClusteringResults(r); ri = ResultUtil.getIterableResults(r); if(ra == null && ro == null && rc == null && ri == null) { throw new UnableToComplyException("No printable result found."); } NamingScheme naming = null; // Process groups or all data in a flat manner? if(rc != null && rc.size() > 0) { groups = new HashSet<DatabaseObjectGroup>(rc.get(0).getAllClusters()); // force an update of cluster names. naming = new SimpleEnumeratingScheme(rc.get(0)); } else { groups = new ArrayList<DatabaseObjectGroup>(); groups.add(new DatabaseObjectGroupCollection<Collection<Integer>>(db.getIDs())); } List<AttributeSettings> settings = ResultUtil.getGlobalAssociation((MultiResult)r, AssociationID.META_SETTINGS); if(ri != null && ri.size() > 0) { writeIterableResult(db, streamOpener, ri.get(0), settings); } if(groups != null) { for(DatabaseObjectGroup group : groups) { writeGroupResult(db, streamOpener, group, ra, ro, naming, settings); } } } private void printObject(TextWriterStream out, O obj, List<Pair<String, Object>> anns) throws UnableToComplyException, IOException { // Write database element itself. { TextWriterWriterInterface<?> owriter = out.getWriterFor(obj); if(owriter == null) { throw new UnableToComplyException("No handler for database object itself: " + obj.getClass().getSimpleName()); } owriter.writeObject(out, null, obj); } // print the annotations if(anns != null) { for(Pair<String, Object> a : anns) { if(a.getSecond() == null) { continue; } TextWriterWriterInterface<?> writer = out.getWriterFor(a.getSecond()); if(writer == null) { throw new UnableToComplyException("No handler for annotation " + a.getFirst() + " in Output: " + a.getSecond().getClass().getSimpleName()); } writer.writeObject(out, a.getFirst(), a.getSecond()); } } out.flush(); } private void writeGroupResult(Database<O> db, StreamFactory streamOpener, DatabaseObjectGroup group, List<AnnotationResult<?>> ra, List<OrderingResult> ro, NamingScheme naming, List<AttributeSettings> settings) throws FileNotFoundException, UnableToComplyException, IOException { String filename = null; // for clusters, use naming. if(group instanceof Cluster) { if(naming != null) { filename = filenameFromLabel(naming.getNameFor(group)); } } PrintStream outStream = streamOpener.openStream(filename); TextWriterStream out = new TextWriterStreamNormalizing<O>(outStream, writers, getNormalization()); printSettings(db, out, settings); // print group information... if(group instanceof TextWriteable) { TextWriterWriterInterface<?> writer = out.getWriterFor(group); out.commentPrintLn("Group class: " + group.getClass().getCanonicalName()); if(writer != null) { writer.writeObject(out, null, group); out.commentPrintSeparator(); out.flush(); } } // print ids. Collection<Integer> ids = group.getIDs(); Iterator<Integer> iter = ids.iterator(); // apply sorting. if(ro != null && ro.size() > 0) { try { iter = ro.get(0).iter(ids); } catch (Exception e) { logger.warning("Exception while trying to sort results.",e); } } while(iter.hasNext()) { Integer objID = iter.next(); if(objID == null) { // shoulnd't really happen? continue; } O obj = db.get(objID.intValue()); if(obj == null) { continue; } // do we have annotations to print? List<Pair<String, Object>> objs = new ArrayList<Pair<String, Object>>(); if(ra != null) { for (AnnotationResult a : ra) { objs.add(new Pair<String, Object>(a.getAssociationID().getLabel(), a.getValueFor(objID))); } } // print the object with its annotations. printObject(out, obj, objs); } out.commentPrintSeparator(); out.flush(); } private void writeIterableResult(Database<O> db, StreamFactory streamOpener, IterableResult<?> ri, List<AttributeSettings> settings) throws UnableToComplyException, IOException { String filename = "list"; PrintStream outStream = streamOpener.openStream(filename); TextWriterStream out = new TextWriterStreamNormalizing<O>(outStream, writers, getNormalization()); printSettings(db, out, settings); // hack to print collectionResult header information if(ri instanceof CollectionResult<?>) { for(String header : ((CollectionResult<?>) ri).getHeader()) { out.commentPrintLn(header); } out.flush(); } Iterator<?> i = ri.iter(); while(i.hasNext()) { Object o = i.next(); TextWriterWriterInterface<?> writer = out.getWriterFor(o); if(writer != null) { writer.writeObject(out, null, o); } out.flush(); } out.commentPrintSeparator(); out.flush(); } /** * Setter for normalization * * @param normalization new normalization object */ public void setNormalization(Normalization<O> normalization) { this.normalization = normalization; } /** * Getter for normalization * * @return normalization object */ public Normalization<O> getNormalization() { return normalization; } /** * Derive a file name from the cluster label. * * @param label cluster label * @return cleaned label suitable for file names. */ private String filenameFromLabel(String label) { return label.toLowerCase().replaceAll("[^a-zA-Z0-9_.\\[\\]-]", "_"); } }
import java.lang.StringBuilder; class AvlTree<T extends Comparable<? super T>> { /** * AvlNode is a container class that is used to store each element * (node) of an AVL tree. * * @author Justin Ethier */ protected static class AvlNode<T> { /** * Node data */ protected T element; /** * Left child */ protected AvlNode<T> left; /** * Right child */ protected AvlNode<T> right; /** * Height of node */ protected int height; /** * Constructor; creates a node without any children * * @param theElement The element contained in this node */ public AvlNode (T theElement){ this (theElement, null, null); } /** * Constructor; creates a node with children * * @param theElement The element contained in this node * @param lt Left child * @param rt Right child */ public AvlNode (T theElement, AvlNode<T> lt, AvlNode<T> rt){ element = theElement; left = lt; right = rt; } } private AvlNode<T> root; // TODO: make these optional based on some sort of 'debug' flag? // at the very least, make them read-only properties public int countInsertions; public int countSingleRotations; public int countDoubleRotations; /** * Avl Tree Constructor. * * Creates an empty tree */ public AvlTree (){ root = null; countInsertions = 0; countSingleRotations = 0; countDoubleRotations = 0; } /** * Determine the height of the given node. * * @param t Node * @return Height of the given node. */ public int height (AvlNode<T> t){ return t == null ? -1 : t.height; } /** * Find the maximum value among the given numbers. * * @param a First number * @param b Second number * @return Maximum value */ public int max (int a, int b){ if (a > b) return a; return b; } /** * Insert an element into the tree. * * @param x Element to insert into the tree * @return True - Success, the Element was added. * False - Error, the element was a duplicate. */ public boolean insert (T x){ try { root = insert (x, root); countInsertions++; return true; } catch(Exception e){ // TODO: catch a DuplicateValueException instead! return false; } } /** * Internal method to perform an actual insertion. * * @param x Element to add * @param t Root of the tree * @return New root of the tree * @throws Exception */ protected AvlNode<T> insert (T x, AvlNode<T> t) throws Exception{ if (t == null) t = new AvlNode<T> (x); else if (x.compareTo (t.element) < 0){ t.left = insert (x, t.left); if (height (t.left) - height (t.right) == 2){ if (x.compareTo (t.left.element) < 0){ t = rotateWithLeftChild (t); countSingleRotations++; } else { t = doubleWithLeftChild (t); countDoubleRotations++; } } } else if (x.compareTo (t.element) > 0){ t.right = insert (x, t.right); if ( height (t.right) - height (t.left) == 2) if (x.compareTo (t.right.element) > 0){ t = rotateWithRightChild (t); countSingleRotations++; } else{ t = doubleWithRightChild (t); countDoubleRotations++; } } else { throw new Exception("Attempting to insert duplicate value"); } t.height = max (height (t.left), height (t.right)) + 1; return t; } /** * Rotate binary tree node with left child. * For AVL trees, this is a single rotation for case 1. * Update heights, then return new root. * * @param k2 Root of tree we are rotating * @return New root */ protected AvlNode<T> rotateWithLeftChild (AvlNode<T> k2){ AvlNode<T> k1 = k2.left; k2.left = k1.right; k1.right = k2; k2.height = max (height (k2.left), height (k2.right)) + 1; k1.height = max (height (k1.left), k2.height) + 1; return (k1); } /** * Double rotate binary tree node: first left child * with its right child; then node k3 with new left child. * For AVL trees, this is a double rotation for case 2. * Update heights, then return new root. * * @param k3 Root of tree we are rotating * @return New root */ protected AvlNode<T> doubleWithLeftChild (AvlNode<T> k3){ k3.left = rotateWithRightChild (k3.left); return rotateWithLeftChild (k3); } /** * Rotate binary tree node with right child. * For AVL trees, this is a single rotation for case 4. * Update heights, then return new root. * * @param k1 Root of tree we are rotating. * @return New root */ protected AvlNode<T> rotateWithRightChild (AvlNode<T> k1){ AvlNode<T> k2 = k1.right; k1.right = k2.left; k2.left = k1; k1.height = max (height (k1.left), height (k1.right)) + 1; k2.height = max (height (k2.right), k1.height) + 1; return (k2); } /** * Double rotate binary tree node: first right child * with its left child; then node k1 with new right child. * For AVL trees, this is a double rotation for case 3. * Update heights, then return new root. * * @param k1 Root of tree we are rotating * @return New root */ protected AvlNode<T> doubleWithRightChild (AvlNode<T> k1){ k1.right = rotateWithLeftChild (k1.right); return rotateWithRightChild (k1); } /** * Serialize the tree to a string using an infix traversal. * * In other words, the tree items will be serialized in numeric order. * * @return String representation of the tree */ public String serializeInfix(){ StringBuilder str = new StringBuilder(); serializeInfix (root, str, " "); return str.toString(); } /** * Internal method to infix-serialize a tree. * * @param t Tree node to traverse * @param str Accumulator; string to keep appending items to. */ protected void serializeInfix(AvlNode<T> t, StringBuilder str, String sep){ if (t != null){ serializeInfix (t.left, str, sep); str.append(t.element.toString()); str.append(sep); serializeInfix (t.right, str, sep); } } /** * Serialize the tree to a string using a prefix traversal. * * In other words, the tree items will be serialized in the order that * they are stored within the tree. * * @return String representation of the tree */ public String serializePrefix(){ StringBuilder str = new StringBuilder(); serializePrefix (root, str, " "); return str.toString(); } /** * Internal method to prefix-serialize a tree. * * @param t Tree node to traverse * @param str Accumulator; string to keep appending items to. */ private void serializePrefix (AvlNode<T> t, StringBuilder str, String sep){ if (t != null){ str.append(t.element.toString()); str.append(sep); serializePrefix (t.left, str, sep); serializePrefix (t.right, str, sep); } } /** * Deletes all nodes from the tree. * */ public void makeEmpty(){ root = null; } /** * Determine if the tree is empty. * * @return True if the tree is empty */ public boolean isEmpty(){ return (root == null); } /** * Find the smallest item in the tree. * @return smallest item or null if empty. */ public T findMin( ) { if( isEmpty( ) ) return null; return findMin( root ).element; } /** * Find the largest item in the tree. * @return the largest item of null if empty. */ public T findMax( ) { if( isEmpty( ) ) return null; return findMax( root ).element; } /** * Internal method to find the smallest item in a subtree. * @param t the node that roots the tree. * @return node containing the smallest item. */ private AvlNode<T> findMin(AvlNode<T> t) { if( t == null ) return t; while( t.left != null ) t = t.left; return t; } /** * Internal method to find the largest item in a subtree. * @param t the node that roots the tree. * @return node containing the largest item. */ private AvlNode<T> findMax( AvlNode<T> t ) { if( t == null ) return t; while( t.right != null ) t = t.right; return t; } // but it needs some attention and does not appear to be 100% correct /** * Remove from the tree. Nothing is done if x is not found. * @param x the item to remove. */ public void remove( T x ) { root = remove(x, root); } public AvlNode<T> remove(T x, AvlNode<T> t) { if (t==null) { System.out.println("Sorry but you're mistaken, " + t + " doesn't exist in this tree :)\n"); return null; } System.out.println("Remove starts... " + t.element + " and " + x); if (x.compareTo(t.element) < 0 ) { t.left = remove(x,t.left); int l = t.left != null ? t.left.height : 0; if((t.right != null) && (t.right.height - l >= 2)) { int rightHeight = t.right.right != null ? t.right.right.height : 0; int leftHeight = t.right.left != null ? t.right.left.height : 0; if(rightHeight >= leftHeight) t = rotateWithLeftChild(t); else t = doubleWithRightChild(t); } } else if (x.compareTo(t.element) > 0) { t.right = remove(x,t.right); int r = t.right != null ? t.right.height : 0; if((t.left != null) && (t.left.height - r >= 2)) { int leftHeight = t.left.left != null ? t.left.left.height : 0; int rightHeight = t.left.right != null ? t.left.right.height : 0; if(leftHeight >= rightHeight) t = rotateWithRightChild(t); else t = doubleWithLeftChild(t); } } /* Here, we have ended up when we are node which shall be removed. Check if there is a left-hand node, if so pick out the largest element out, and move down to the root. */ else if(t.left != null) { t.element = findMax(t.left).element; remove(t.element, t.left); if((t.right != null) && (t.right.height - t.left.height >= 2)) { int rightHeight = t.right.right != null ? t.right.right.height : 0; int leftHeight = t.right.left != null ? t.right.left.height : 0; if(rightHeight >= leftHeight) t = rotateWithLeftChild(t); else t = doubleWithRightChild(t); } } else t = (t.left != null) ? t.left : t.right; if(t != null) { int leftHeight = t.left != null ? t.left.height : 0; int rightHeight = t.right!= null ? t.right.height : 0; t.height = Math.max(leftHeight,rightHeight) + 1; } return t; } //End of remove... /** * Search for an element within the tree. * * @param x Element to find * @param t Root of the tree * @return True if the element is found, false otherwise */ public boolean find(T x){ // TODO: would be more useful to store key/value, // and use key to perform the lookup here... return find(x, root); } /** * Internal find method; search for an element starting at the given node. * * @param x Element to find * @param t Root of the tree * @return True if the element is found, false otherwise */ protected boolean find(T x, AvlNode<T> t) { if (t == null){ return false; // The node was not found } else if (x.compareTo(t.element) < 0){ return find(x, t.left); } else if (x.compareTo(t.element) > 0){ return find(x, t.right); } return true; // Can only reach here if node was found } /** * Main entry point; contains test code for the tree. */ public static void main () { //String []args){ AvlTree<Integer> t = new AvlTree<Integer>(); t.insert (new Integer(2)); t.insert (new Integer(1)); t.insert (new Integer(4)); t.insert (new Integer(5)); t.insert (new Integer(9)); t.insert (new Integer(3)); t.insert (new Integer(6)); t.insert (new Integer(7)); System.out.println ("Infix Traversal:"); System.out.println(t.serializeInfix()); System.out.println ("Prefix Traversal:"); System.out.println(t.serializePrefix()); } }
package de.smits_net.games.framework.character; import de.smits_net.games.framework.board.Board; import de.smits_net.games.framework.image.AnimatedImage; import de.smits_net.games.framework.sprite.DirectionAnimatedSprite; import java.awt.Point; /** * Base class for moveable characters in the game. Characters are similar * to sprites with the difference that they have a target location and move * to this location with a given speed and then stop there. */ public class Character extends DirectionAnimatedSprite { /** Position where the character should move to */ protected Point target; /** The speed the character moves with */ protected int speed; /** * Create a new sprite. * * @param board our board * @param startPoint start position * @param speed the speed of the object * @param policy policy used when sprite reaches * @param noDirection animation for no direction * @param west animation for movement to the west * @param east animation for movement to the east * @param north animation for movement north * @param south animation for movement south * @param noMovementWest animation for non-moving sprite, facing to the west * @param noMovementEast animation for non-moving sprite, facing to the east * @param noMovementNorth animation for non-moving sprite, facing to the north * @param noMovementSouth animation for non-moving sprite, facing to the south */ public Character(Board board, Point startPoint, int speed, BoundaryPolicy policy, AnimatedImage noDirection, AnimatedImage west, AnimatedImage east, AnimatedImage north, AnimatedImage south, AnimatedImage noMovementWest, AnimatedImage noMovementEast, AnimatedImage noMovementNorth, AnimatedImage noMovementSouth) { super(board, startPoint, policy, noDirection, north, null, east, null, south, null, west, null, noMovementNorth, null, noMovementEast, null, noMovementSouth, noMovementWest, null, null); // start with target = position target = (Point)startPoint.clone(); this.speed = speed; } /** * Sets the target position of the character. * * @param target target position */ public void setTarget(Point target) { Point newTarget = (Point)(target.clone()); // ensure that we do not move outside the bounds if (newTarget.x < bounds.x) { newTarget.x = bounds.x; } if (newTarget.y < bounds.y) { newTarget.y = bounds.y; } if (newTarget.x > bounds.x + bounds.width) { newTarget.x = bounds.x + bounds.width; } if (newTarget.y > bounds.y + bounds.height) { newTarget.y = bounds.y + bounds.height; } this.target = newTarget; } @Override public void move() { // distance to the new point double distanceX = Math.round(target.x - position.x); double distanceY = Math.round(target.y - position.y); if (Math.abs(distanceX) < 0.1 && Math.abs(distanceY) < 0.1 ) { // are we already there? return; } // angle between the current position and the target double alpha = Math.atan(distanceY / distanceX); if (Math.abs(alpha) < 0.01) { // it is a horizontal movement velocity.x = speed * Math.signum(distanceX); velocity.y = 0.0; } else { // some diagonal or vertical movement velocity.x = Math.cos(alpha) * speed; velocity.y = Math.sin(alpha) * speed; } // calculate distance (squared) double lengthSpeedVector = velocity.x*velocity.x + velocity.y*velocity.y; double lengthDistance = distanceX*distanceX + distanceY*distanceY; if (lengthDistance < lengthSpeedVector) { // we would reach the target with the given speed vector // in one step. To avoid overshooting, jump to the target velocity.x = 0; velocity.y = 0; position.x = target.x; position.y = target.y; } else { // get nearer the target with the given speed vector position.x += velocity.x; position.y += velocity.y; } // ensure that we stay inside our boundaries ensureBoundaryPolicy(); } }
package de.ust.skill.common.java.internal.fieldTypes; import java.io.IOException; import java.util.Collection; import de.ust.skill.common.jvm.streams.InStream; import de.ust.skill.common.jvm.streams.OutStream; public final class V64 extends IntegerType<Long> { private final static V64 instance = new V64(); public static V64 get() { return instance; } private V64() { super(11); } @Override public Long readSingleField(InStream in) { return in.v64(); } @Override public long calculateOffset(Collection<Long> xs) { long result = 0L; for (long v : xs) { if (0L == (v & 0xFFFFFFFFFFFFFF80L)) { result += 1; } else if (0L == (v & 0xFFFFFFFFFFFFC000L)) { result += 2; } else if (0L == (v & 0xFFFFFFFFFFE00000L)) { result += 3; } else if (0L == (v & 0xFFFFFFFFF0000000L)) { result += 4; } else if (0L == (v & 0xFFFFFFF800000000L)) { result += 5; } else if (0L == (v & 0xFFFFFC0000000000L)) { result += 6; } else if (0L == (v & 0xFFFE000000000000L)) { result += 7; } else if (0L == (v & 0xFF00000000000000L)) { result += 8; } else { result += 9; } } return result; } @Override public long singleOffset(Long v) { if (0L == (v & 0xFFFFFFFFFFFFFF80L)) { return 1; } else if (0L == (v & 0xFFFFFFFFFFFFC000L)) { return 2; } else if (0L == (v & 0xFFFFFFFFFFE00000L)) { return 3; } else if (0L == (v & 0xFFFFFFFFF0000000L)) { return 4; } else if (0L == (v & 0xFFFFFFF800000000L)) { return 5; } else if (0L == (v & 0xFFFFFC0000000000L)) { return 6; } else if (0L == (v & 0xFFFE000000000000L)) { return 7; } else if (0L == (v & 0xFF00000000000000L)) { return 8; } else { return 9; } } @Override public void writeSingleField(Long target, OutStream out) throws IOException { out.v64(target); } @Override public String toString() { return "v64"; } /** * helper method used by other offset calculations */ public final static long singleV64Offset(int v) { if (0 == (v & 0xFFFFFF80)) { return 1; } else if (0 == (v & 0xFFFFC000)) { return 2; } else if (0 == (v & 0xFFE00000)) { return 3; } else if (0 == (v & 0xF0000000)) { return 4; } else { return 5; } } /** * helper method used by other offset calculations */ public final static long singleV64Offset(long v) { if (0L == (v & 0xFFFFFFFFFFFFFF80L)) { return 1; } else if (0L == (v & 0xFFFFFFFFFFFFC000L)) { return 2; } else if (0L == (v & 0xFFFFFFFFFFE00000L)) { return 3; } else if (0L == (v & 0xFFFFFFFFF0000000L)) { return 4; } else if (0L == (v & 0xFFFFFFF800000000L)) { return 5; } else if (0L == (v & 0xFFFFFC0000000000L)) { return 6; } else if (0L == (v & 0xFFFE000000000000L)) { return 7; } else if (0L == (v & 0xFF00000000000000L)) { return 8; } else { return 9; } } }
package dk.netarkivet.wayback.aggregator; import java.io.File; import java.util.LinkedList; import java.util.List; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.wayback.WaybackSettings; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Encapsulates the functionality for sorting and merging index files. Uses the * Unix sort cmd for optimized sorting and file merging. Operations in this * class are synchronized to avoid multiple jobs running at the same time (by * the same object at least). */ public class IndexAggregator { /** The logger for this class. */ private Log log = LogFactory.getLog(getClass().getName()); /** * Generates a sorted CDX index file based on the set of unsorted CDX input * files.<p> The operation will not run on a folder which already has a * process job running. * * @param files A list of the files to aggregate * @param outputFile Name of the outputfile. In case of a empty filesNames * array no outputFiles will be generated */ public void sortAndMergeFiles(File[] files, File outputFile) { processFiles(files, outputFile, null); } /** * Takes a list of sorted files and merges them. * @param files The files to merge. * @param outputFile The resulting file containing total sorted set of index lines found in all the provided index files */ public void mergeFiles(File[] files, File outputFile) { List<String> args = new LinkedList<String>(); args.add("-m"); processFiles(files, outputFile, args); } /** * Calls the Unix sort command with the options <code>$filesNames -o * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR. * * Sets the LC_ALL environment variable before making the call. * * @param files The files to merge and sort * @param outputFile The resulting sorted file * @param additionalArgs A list af extra arguments, which (if different from * null) are added to the sort call.<p> Note: If any * of the args contain a whitespace the call will * fail. */ private void processFiles(File[] files, File outputFile, List<String> additionalArgs) { if (files.length == 0) { return; } // Empty file list will cause sort to wait for further input, and the call will therefor never return Process p = null; try { List<String> inputFileList = new LinkedList<String>(); for (int i = 0; i < files.length; i++) { if (files[i].exists() && files[i].isFile()) { inputFileList.add(files[i].getCanonicalPath()); } else { log.warn("File "+files[i] +" doesn't exist or isn't a regular file, dropping from list of files to " + "sort and merge"); } } List<String> cmd = new LinkedList<String>(); // Prepare to run the unix sort command, see sort manual page for details cmd.add("sort"); cmd.addAll(inputFileList); cmd.add("-o"); cmd.add(outputFile.getCanonicalPath()); cmd.add("-T"); cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR)); if (additionalArgs != null && !additionalArgs.isEmpty()) { for (String argument:additionalArgs) { ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1, "The argument '"+argument+"' contains spaces, this isn't allowed "); } cmd.addAll(additionalArgs); } ProcessBuilder pb = new ProcessBuilder(cmd); // Reset all locale definitions pb.environment().put("LC_ALL", "C"); // Run the command in the user.dir directory pb.directory(new File(System.getProperty("user.dir"))); p = pb.start(); p.waitFor(); if (p.exitValue() != 0) { log.error( "Failed to sort index files, sort exited with return code " + p.exitValue()); } } catch (Exception e) { log.error("Failed to aggregate indexes ", e); } } }
package dr.inference.trace; import java.io.File; import java.io.FileNotFoundException; import java.util.*; import dr.util.Attribute; import dr.util.FileHelpers; import dr.xml.*; /** * @author Guy Baele */ public class SteppingStoneSamplingAnalysis { public static final String STEPPING_STONE_SAMPLING_ANALYSIS = "steppingStoneSamplingAnalysis"; public static final String LIKELIHOOD_COLUMN = "likelihoodColumn"; public static final String THETA_COLUMN = "thetaColumn"; public static final String FORMAT = "%5.5g"; private final String logLikelihoodName; private final List<Double> logLikelihoodSample; private final List<Double> thetaSample; private boolean logBayesFactorCalculated = false; private double logBayesFactor; private List<Double> maxLogLikelihood; private List<Double> orderedTheta; public SteppingStoneSamplingAnalysis(String logLikelihoodName, List<Double> logLikelihoodSample, List<Double> thetaSample) { this.logLikelihoodSample = logLikelihoodSample; this.logLikelihoodName = logLikelihoodName; this.thetaSample = thetaSample; } public double getLogBayesFactor() { if (!logBayesFactorCalculated) { calculateBF(); } return logBayesFactor; } private void calculateBF() { Map<Double, List<Double>> map = new HashMap<Double, List<Double>>(); orderedTheta = new ArrayList<Double>(); //only the log-likelihoods are needed to calculate the marginal likelihood for (int i = 0; i < logLikelihoodSample.size(); i++) { if (!map.containsKey(thetaSample.get(i))) { map.put(thetaSample.get(i), new ArrayList<Double>()); orderedTheta.add(thetaSample.get(i)); } map.get(thetaSample.get(i)).add(logLikelihoodSample.get(i)); } Collections.sort(orderedTheta); //a list with the maxima of the log-likelihood values is constructed maxLogLikelihood = new ArrayList<Double>(); for (double t : orderedTheta) { List<Double> values = map.get(t); maxLogLikelihood.add(Collections.max(values)); } logBayesFactor = 0.0; for (int i = 1; i < orderedTheta.size(); i++) { logBayesFactor += (orderedTheta.get(i) - orderedTheta.get(i-1)) * maxLogLikelihood.get(i); } for (int i = 1; i < orderedTheta.size(); i++) { double internalSum = 0.0; for (int j = 0; j < map.get(orderedTheta.get(i-1)).size(); j++) { internalSum += Math.exp((orderedTheta.get(i) - orderedTheta.get(i-1)) * (map.get(orderedTheta.get(i-1)).get(j) - maxLogLikelihood.get(i))); } internalSum /= map.get(orderedTheta.get(i-1)).size(); logBayesFactor += Math.log(internalSum); } logBayesFactorCalculated = true; } public String toString() { double bf = getLogBayesFactor(); StringBuffer sb = new StringBuffer(); sb.append("PathParameter\tMaxPathLikelihood\n"); for (int i = 0; i < orderedTheta.size(); ++i) { sb.append(String.format(FORMAT, orderedTheta.get(i))); sb.append("\t"); sb.append(String.format(FORMAT, maxLogLikelihood.get(i))); sb.append("\n"); } sb.append("\nlog marginal likelihood (using stepping stone sampling) from " + logLikelihoodName + " = " + bf + "\n"); return sb.toString(); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return STEPPING_STONE_SAMPLING_ANALYSIS; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME); StringTokenizer tokenFileName = new StringTokenizer(fileName); int numberOfFiles = tokenFileName.countTokens(); System.out.println(numberOfFiles + " file(s) found with marginal likelihood samples"); try { String likelihoodName = ""; List sampleLogLikelihood = null; List sampleTheta = null; for (int j = 0; j < numberOfFiles; j++) { File file = new File(tokenFileName.nextToken()); String name = file.getName(); String parent = file.getParent(); if (!file.isAbsolute()) { parent = System.getProperty("user.dir"); } file = new File(parent, name); fileName = file.getAbsolutePath(); XMLObject cxo = xo.getChild(LIKELIHOOD_COLUMN); likelihoodName = cxo.getStringAttribute(Attribute.NAME); cxo = xo.getChild(THETA_COLUMN); String thetaName = cxo.getStringAttribute(Attribute.NAME); LogFileTraces traces = new LogFileTraces(fileName, file); traces.loadTraces(); int burnin = 0; traces.setBurnIn(burnin); int traceIndexLikelihood = -1; int traceIndexTheta = -1; for (int i = 0; i < traces.getTraceCount(); i++) { String traceName = traces.getTraceName(i); if (traceName.trim().equals(likelihoodName)) { traceIndexLikelihood = i; } if (traceName.trim().equals(thetaName)) { traceIndexTheta = i; } } if (traceIndexLikelihood == -1) { throw new XMLParseException("Column '" + likelihoodName + "' can not be found for " + getParserName() + " element."); } if (traceIndexTheta == -1) { throw new XMLParseException("Column '" + thetaName + "' can not be found for " + getParserName() + " element."); } if (sampleLogLikelihood == null && sampleTheta == null) { sampleLogLikelihood = traces.getValues(traceIndexLikelihood); sampleTheta = traces.getValues(traceIndexTheta); } else { sampleLogLikelihood.addAll(traces.getValues(traceIndexLikelihood)); sampleTheta.addAll(traces.getValues(traceIndexTheta)); } } SteppingStoneSamplingAnalysis analysis = new SteppingStoneSamplingAnalysis(likelihoodName, sampleLogLikelihood, sampleTheta); System.out.println(analysis.toString()); return analysis; } catch (FileNotFoundException fnfe) { throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element."); } catch (java.io.IOException ioe) { throw new XMLParseException(ioe.getMessage()); } catch (TraceException e) { throw new XMLParseException(e.getMessage()); } }
package edu.washington.escience.myriad.operator; import java.io.Serializable; import java.util.Arrays; import edu.washington.escience.myriad.DbException; import edu.washington.escience.myriad.Schema; import edu.washington.escience.myriad.TupleBatch; /** * Abstract class for implementing operators. * * @author slxu * * Currently, the operator api design requires that each single operator instance should be executed within a * single thread. * * No multi-thread synchronization is considered. * */ public abstract class Operator implements Serializable { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * A single buffer for temporally holding a TupleBatch for pull. * */ private TupleBatch outputBuffer = null; /** * A bit denoting whether the operator is open (initialized). * */ private boolean open = false; /** * EOS. Initially set it as true; * */ private boolean eos = true; private boolean eoi = true; /** * Closes this iterator. * * @throws DbException if any errors occur */ public final void close() throws DbException { // Ensures that a future call to next() will fail outputBuffer = null; open = false; eos = true; eoi = true; cleanup(); Operator[] children = getChildren(); if (children != null) { for (Operator child : children) { if (child != null) { child.close(); } } } } /** * Check if currently there's any TupleBatch available for pull. * * This method is non-blocking. * * @throws DbException if any problem * * @return if currently there's output for pulling. * * */ public final boolean nextReady() throws DbException { if (!open) { throw new DbException("Operator not yet open"); } if (eos()) { throw new DbException("Operator already eos"); } if (outputBuffer == null) { outputBuffer = fetchNextReady(); while (outputBuffer != null && outputBuffer.numTuples() <= 0) { // XXX while or not while? For a single thread operator, while sounds more efficient generally outputBuffer = fetchNextReady(); } } return outputBuffer == null; } /** * Check if EOS is meet. * * This method is non-blocking. * * @return if the Operator is EOS * * */ public final boolean eos() { return eos; } public final boolean eoi() { return eoi; } public final TupleBatch next() throws DbException { if (!open) { throw new IllegalStateException("Operator not yet open"); } if (eos() || eoi()) { return null; } TupleBatch result = null; if (outputBuffer != null) { result = outputBuffer; } else { result = fetchNext(); } outputBuffer = null; while (result != null && result.numTuples() <= 0) { result = fetchNext(); } if (result == null) { Operator[] children = getChildren(); boolean[] childrenEOI = getChildrenEOI(); boolean allEOS = true; int count = 0; for (int i = 0; i < children.length; ++i) { if (children[i].eos()) { childrenEOI[i] = true; } else if (children[i].eoi()) { childrenEOI[i] = true; children[i].setEOI(false); allEOS = false; } if (childrenEOI[i]) { count++; } } if (count == children.length) { if (allEOS) { setEOS(); } else { setEOI(true); } cleanChildrenEOI(); } } return result; } /** * open the operator and do initializations. * * @throws DbException if any error occurs * */ public final void open() throws DbException { // open the children first if (open) { // XXX Do some error handling to multi-open? throw new DbException("Operator already open."); } Operator[] children = getChildren(); if (children != null) { for (Operator child : children) { if (child != null) { child.open(); } } } eos = false; // do my initialization init(); open = true; } /** * Explicitly set EOS for this operator. * * Only call this method if the operator is a leaf operator. * * */ protected final void setEOS() { eos = true; } protected final void setEOI(boolean x) { eos = x; } public boolean isOpen() { return open; } /** * Do the initialization of this operator. * * @throws DbException if any error occurs * */ protected abstract void init() throws DbException; /** * Do the clean up, release resources. * * @throws DbException if any error occurs * */ protected abstract void cleanup() throws DbException; /** * Generate next output TupleBatch if possible. Return null immediately if currently no output can be generated. * * Do not block the execution thread in this method, including sleep, wait on locks, etc. * * @throws DbException if any error occurs * * @return next ready output TupleBatch. null if either EOS or no output TupleBatch can be generated currently. * */ protected abstract TupleBatch fetchNextReady() throws DbException; /** * @return return the Schema of the output tuples of this operator. * */ public abstract Schema getSchema(); /** * Returns the next output TupleBatch, or null if EOS is meet. * * This method is blocking. * * * @return the next output TupleBatch, or null if EOS * * @throws DbException if any processing error occurs * */ protected abstract TupleBatch fetchNext() throws DbException; /** * @return return the children Operators of this operator. If there is only one child, return an array of only one * element. For join operators, the order of the children is not important. But they should be consistent * among multiple calls. */ public abstract Operator[] getChildren(); /** * Set the children(child) of this operator. If the operator has only one child, children[0] should be used. If the * operator is a join, children[0] and children[1] should be used. * * * @param children the Operators which are to be set as the children(child) of this operator */ // have we ever used this function? public abstract void setChildren(Operator[] children); public boolean[] childrenEOI = null; public boolean[] getChildrenEOI() { if (childrenEOI == null) { childrenEOI = new boolean[getChildren().length]; } return childrenEOI; } public void cleanChildrenEOI() { Arrays.fill(childrenEOI, false); } }
package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.UUID; import org.jdom.JDOMException; /** * @author Jaroslaw Krych * */ public interface ApplicationManager { public boolean loadApplications (File xipAppFile) throws JDOMException, IOException; public boolean storeApplications(List<Application> applications, File xipAppFile); public boolean addApplication(Application newApplication); public boolean modifyApplication(UUID applicationUUID, Application modifiedApplication); public boolean removeApplication(UUID applicationUUID); public Application getApplication(UUID uuid); public Application getApplication(String applicationName); public List<Application> getApplications(); public int getNumberOfApplications(); public URL generateNewApplicationServiceURL(); public URL generateNewHostServiceURL(); public void setTmpDir(File tmpDir); public File getTmpDir(); public void setOutputDir(File outDir); public File getOutputDir(); }
package gameAuthoringEnvironment.levelEditor; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Scanner; import java.util.Map; import java.util.Vector; import gameEngine.GameObject; import gameEngine.Level; import gameEngine.UninstantiatedGameObject; import javax.swing.JPanel; import jgame.JGColor; import jgame.JGObject; import jgame.JGPoint; import jgame.JGRectangle; import jgame.platform.JGEngine; public class LevelEditor extends JGEngine { private GameObject selectedObject; private static final String default_path = "src/gameAuthoringEnvironment/levelEditor/Resources/initObject"; private static final int MAX_FRAME_SKIP = 3; private static final int FRAMES_PER_SECOND = 250; private static final int SCREEN_HEIGHT = 600; private static final int SCREEN_WIDTH = 600; // TODO Why is this public? public LevelMover myMover; private Map<String, String> imageMap = new HashMap<String, String>(); private Level myLevel; private static final int INITIAL_WIDTH = 600; private static final int INITIAL_HEIGHT = 600; private static final int BLOCK_SIZE_X = 300; private static final int BLOCK_SIZE_Y = 300; private static final int BALL_OFF_SCREEN_ADJUSTMENT_X_LEFTSIDE = 5; private static final int BALL_OFF_SCREEN_ADJUSTMENT_X_RIGHTSIDE = 10; private static final int BALL_OFF_SCREEN_ADJUSTMENT_Y_TOP = 5; private static final int BALL_OFF_SCREEN_ADJUSTMENT_Y_BOTTOM = 10; private ObjectStatsPanel myObjectStatsPanel; private final String defaultImage = "/gameAuthoringEnvironment/levelEditor/Resources/red.gif"; private static int COLID_FOR_PLAYER = 1; private static int COLID_FOR_ENEMY = 4; private static int COLID_FOR_BLOCK = 2; private static int COLID_FOR_GOAL = 8; /** * JGame class that holds the level editor. This displays what the created * level currently looks like. * * @param level * Level being edited */ public LevelEditor(Level level) { super(); myLevel = level; //dbgShowMessagesInPf(false); dbgIsEmbedded(true); initEngine((int) SCREEN_WIDTH, SCREEN_HEIGHT); // This just hides the null pointer exception error. If it ends up // affecting anything, we can change it. defineMedia("tempTable.tbl"); defineImage("firebackground","m",0,"firebackground.jpg","-"); defineImage("srball", "n", 0, defaultImage, "-"); myMover = new LevelMover(this); setBGImage(myLevel.getBackground()); try { fillImageMap(new File(default_path)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public Level getLevel() { return myLevel; } public void setObjectStatsPanel(ObjectStatsPanel panel) { myObjectStatsPanel = panel; } @Override public void initCanvas() { setCanvasSettings(1, 1, BLOCK_SIZE_X, BLOCK_SIZE_Y, null, JGColor.white, null); } @Override public void initGame() { setFrameRate(FRAMES_PER_SECOND, MAX_FRAME_SKIP); // width in spot 0, height in spot 1 setPFSize(myLevel.getLevelSize().x, myLevel.getLevelSize().y); } /** * Adds an object to the level and instantiates it * * @param imageName * name of image * @param x * x position of image * @param y * y position of image */ public void addObject(String imageName, int x, int y) { UninstantiatedGameObject newObject; if (myObjectStatsPanel.getObjectName().equals("Player")) { Map<Integer, String> levelInputMap = new HashMap<Integer, String>(); levelInputMap.put(39, "moveRight"); levelInputMap.put(37, "moveLeft"); levelInputMap.put(40, "moveDown"); levelInputMap.put(38, "moveUp"); newObject = new UninstantiatedGameObject("player", new JGPoint(x, y), COLID_FOR_PLAYER, imageName, levelInputMap, false); } else if (myObjectStatsPanel.getObjectName().equals("Block")) { newObject = new UninstantiatedGameObject("block", new JGPoint(x, y), COLID_FOR_BLOCK, imageName, true); } else if (myObjectStatsPanel.getObjectName().equals("Enemy")) { newObject = new UninstantiatedGameObject("goomba", new JGPoint(x, y), COLID_FOR_ENEMY, imageName, myObjectStatsPanel .getMovementName().toLowerCase(), myObjectStatsPanel.getMovementSpeed() * 10, myObjectStatsPanel.getMovementDuration(), false); } else if (myObjectStatsPanel.getObjectName().equals("Moving Platform")) { newObject = new UninstantiatedGameObject("moving platform", new JGPoint(x, y), COLID_FOR_BLOCK, imageName, myObjectStatsPanel .getMovementName().toLowerCase(), myObjectStatsPanel.getMovementSpeed() * 10, myObjectStatsPanel.getMovementDuration(), true); } else if (myObjectStatsPanel.getObjectName().equals("Goal")) { newObject = new UninstantiatedGameObject("goal", new JGPoint(x, y), COLID_FOR_GOAL, imageName, true); } else if (myObjectStatsPanel.getObjectName().equals("Scenery")) { newObject = new UninstantiatedGameObject("stationary platform", new JGPoint(x, y), COLID_FOR_PLAYER + 4, imageName, true); } else { newObject = new UninstantiatedGameObject("block", new JGPoint(x, y), COLID_FOR_BLOCK, imageName, true); } myLevel.addObjects(newObject); newObject.instantiate(); } public void setGravity(double value) { myLevel.setGravityVal(value/10); } private void checkInBounds() { if ((Double) myMover.x == null) System.out.println((Double) myMover.x == null); if (myMover.x >= myMover.pfwidth) { // myMover.x=el.xofs; myMover.x = myMover.pfwidth - BALL_OFF_SCREEN_ADJUSTMENT_X_RIGHTSIDE; } if (myMover.y >= myMover.pfheight) { myMover.y = myMover.pfheight - BALL_OFF_SCREEN_ADJUSTMENT_Y_BOTTOM; } if (myMover.x <= 0) { myMover.x = BALL_OFF_SCREEN_ADJUSTMENT_X_LEFTSIDE; } if (myMover.y <= 0) { myMover.y = BALL_OFF_SCREEN_ADJUSTMENT_Y_TOP; } // System.out.println(el.xofs+" "+el.yofs+" "+myMover.x+" "+myMover.y+" "+myMover.pfwidth); } public void fillImageMap(File file) throws FileNotFoundException { Scanner s = new Scanner(file); int i = 1; while (s.hasNext()) { System.out.println(i); String[] str = s.nextLine().split(" "); imageMap.put(str[0], str[1]); defineImage(str[0], "a" + i, 0, str[1], "a" + i); i++; } System.out.println("size " + el.images_loaded.size()); } public Map<String, String> getMap() { return imageMap; } public void doFrame() { checkInBounds(); moveObjects(null, 0); setViewOffset((int) myMover.x, (int) myMover.y, true); // System.out.println(this.el.images_loaded.size()); selectOnClick(); //setBGImage(myLevel.getBackground()); } public void paintFrame() { highlight(selectedObject, JGColor.red); highlight(myMover,JGColor.blue); } public void selectOnClick() { //new JGRectangle() if (getMouseButton(1)) { JGRectangle rect=new JGRectangle(getMouseX()+el.xofs, getMouseY()+el.yofs, 10, 10); Vector<GameObject> v = getObjects("", 0, true, rect); System.out.println(rect); if (v.size() > 0) if( v.get(0) != (JGObject) myMover) selectedObject = v.get(0); //System.out.println(selectedObject.x+" "+selectedObject.y); } } public void highlight(JGObject object, JGColor color) { setColor(JGColor.red); if (object != null) drawRect(object.x, object.y, object.getBBox().width, object.getBBox().height, false, false, 2, color); } // TODO add method to check for collisions with screen boundary, and decide // what to do when screen // shrinks and doesn't include mover. // TODO push a button to place selected object? }
package gov.nih.nci.calab.ui.workflow; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean; import gov.nih.nci.calab.dto.workflow.FileDownloadInfo; import gov.nih.nci.calab.dto.workflow.RunBean; import gov.nih.nci.calab.service.util.ActionUtil; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.file.FileLocatorUtils; import gov.nih.nci.calab.service.util.file.FileNameConvertor; import gov.nih.nci.calab.service.util.file.FilePacker; import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData; import gov.nih.nci.calab.service.util.file.HttpUploadedFileData; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; import gov.nih.nci.calab.ui.core.AbstractDispatchAction; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.apache.struts.validator.DynaValidatorActionForm; /** * This class handle workflow upload process. * * @author zhoujim * */ public class FileDownloadAction extends AbstractDispatchAction { private static org.apache.log4j.Logger logger_ = org.apache.log4j.Logger.getLogger(FileDownloadAction.class); public String fullPathName = null; /** * This method is setting up the parameters for the workflow input upload files * or output upload files. * * @param mapping * @param form * @param request * @param response * @return mapping forward */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); ExecuteWorkflowService workflowService = new ExecuteWorkflowService(); String runId = request.getParameter("runId"); RunBean runBean = workflowService.getAssayInfoByRun((ExecuteWorkflowBean)session.getAttribute("workflow"), runId); DynaValidatorActionForm fileForm = (DynaValidatorActionForm)form; //TODO: get data from database or GUI, currently, all parameters are hardcoded. fileForm.set("assayType", runBean.getAssayBean().getAssayType()); fileForm.set("assay", runBean.getAssayBean().getAssayName()); fileForm.set("run", runBean.getName()); fileForm.set("inout", (request.getParameter("type")).equalsIgnoreCase("in")?"Input" : "Output"); // fileForm.set("assayType", "Prescreening_Assay"); // fileForm.set("assay", "STE_1"); // fileForm.set("run", "run1"); // fileForm.set("inout", "Input"); String contentPath = request.getContextPath(); String path = PropertyReader.getProperty(CalabConstants.FILEUPLOAD_PROPERTY, "inputFileDirectory"); fullPathName = path + fileForm.get("assayType") + File.separator + fileForm.get("assay") + File.separator + fileForm.get("run") + File.separator + fileForm.get("inout") + File.separator + CalabConstants.UNCOMPRESSED_FILE_DIRECTORY; ArrayList fileNameHolder = new ArrayList(); String[] listFiles = new File(fullPathName).list(); String allFileName = CalabConstants.ALL_FILES + ".zip"; for(int i = 0; i < listFiles.length; i++ ) { if (!listFiles[i].equalsIgnoreCase(allFileName)) { FileDownloadInfo fileDownloadInfo = new FileDownloadInfo(); fileDownloadInfo.setFileName(listFiles[i]); fileDownloadInfo.setUploadDate(new Date()); fileDownloadInfo.setAction(contentPath+"/fileDownload.do?method=downloadFile&fileName="+listFiles[i]); fileNameHolder.add(fileDownloadInfo); } } fileForm.set("fileInfoList", fileNameHolder); fileForm.set("downloadAll", contentPath+"/fileDownload.do?method=downloadFile&fileName="+CalabConstants.ALL_FILES+".zip"); return mapping.findForward("success"); } public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorActionForm fileForm = (DynaValidatorActionForm)form; String fileName = (String)fileForm.get("fileName"); File f = new File(fullPathName+File.separator+fileName); ActionUtil actionUtil = new ActionUtil(); actionUtil.writeBinaryStream(f, response); return null; } public boolean loginRequired() { return true; } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.microsoft.live; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.http.client.HttpClient; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.SslErrorHandler; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; /** * AuthorizationRequest performs an Authorization Request by launching a WebView Dialog that * displays the login and consent page and then, on a successful login and consent, performs an * async AccessToken request. */ class AuthorizationRequest implements ObservableOAuthRequest, OAuthRequestObserver { /** * OAuthDialog is a Dialog that contains a WebView. The WebView loads the passed in Uri, and * loads the passed in WebViewClient that allows the WebView to be observed (i.e., when a page * loads the WebViewClient will be notified). */ private class OAuthDialog extends Dialog implements OnCancelListener { /** * AuthorizationWebViewClient is a static (i.e., does not have access to the instance that * created it) class that checks for when the end_uri is loaded in to the WebView and calls * the AuthorizationRequest's onEndUri method. */ private class AuthorizationWebViewClient extends WebViewClient { private final CookieManager cookieManager; private final Set<String> cookieKeys; public AuthorizationWebViewClient() { // I believe I need to create a syncManager before I can use a cookie manager. CookieSyncManager.createInstance(getContext()); this.cookieManager = CookieManager.getInstance(); this.cookieKeys = new HashSet<String>(); } /** * Call back used when a page is being started. * * This will check to see if the given URL is one of the end_uris/redirect_uris and * based on the query parameters the method will either return an error, or proceed with * an AccessTokenRequest. * * @param view {@link WebView} that this is attached to. * @param url of the page being started */ @Override public void onPageFinished(WebView view, String url) { Uri uri = Uri.parse(url); // only clear cookies that are on the logout domain. if (uri.getHost() != null && uri.getHost().equals(Config.INSTANCE.getOAuthLogoutUri().getHost())) { this.saveCookiesInMemory(this.cookieManager.getCookie(url)); } Uri endUri = Config.INSTANCE.getOAuthDesktopUri(); boolean isEndUri = UriComparator.INSTANCE.compare(uri, endUri) == 0; if (!isEndUri) { return; } this.saveCookiesToPreferences(); AuthorizationRequest.this.onEndUri(uri); OAuthDialog.this.dismiss(); } /** * Callback when the WebView received an Error. * * This method will notify the listener about the error and dismiss the WebView dialog. * * @param view the WebView that received the error * @param errorCode the error code corresponding to a WebViewClient.ERROR_* value * @param description the String containing the description of the error * @param failingUrl the url that encountered an error */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { AuthorizationRequest.this.onError("", description, failingUrl); OAuthDialog.this.dismiss(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // TODO: Android does not like the SSL certificate we use, because it has '*' in // it. Proceed with the errors. handler.proceed(); } private void saveCookiesInMemory(String cookie) { // Not all URLs will have cookies if (TextUtils.isEmpty(cookie)) { return; } String[] pairs = TextUtils.split(cookie, "; "); for (String pair : pairs) { int index = pair.indexOf(EQUALS); String key = pair.substring(0, index); this.cookieKeys.add(key); } } private void saveCookiesToPreferences() { SharedPreferences preferences = getContext().getSharedPreferences(PreferencesConstants.FILE_NAME, Context.MODE_PRIVATE); // If the application tries to login twice, before calling logout, there could // be a cookie that was sent on the first login, that was not sent in the second // login. So, read the cookies in that was saved before, and perform a union // with the new cookies. String value = preferences.getString(PreferencesConstants.COOKIES_KEY, ""); String[] valueSplit = TextUtils.split(value, PreferencesConstants.COOKIE_DELIMITER); this.cookieKeys.addAll(Arrays.asList(valueSplit)); Editor editor = preferences.edit(); value = TextUtils.join(PreferencesConstants.COOKIE_DELIMITER, this.cookieKeys); editor.putString(PreferencesConstants.COOKIES_KEY, value); editor.commit(); // we do not need to hold on to the cookieKeys in memory anymore. // It could be garbage collected when this object does, but let's clear it now, // since it will not be used again in the future. this.cookieKeys.clear(); } } /** Uri to load */ private final Uri requestUri; /** * Constructs a new OAuthDialog. * * @param context to construct the Dialog in * @param requestUri to load in the WebView * @param webViewClient to be placed in the WebView */ public OAuthDialog(Uri requestUri) { super(AuthorizationRequest.this.activity, android.R.style.Theme_Translucent_NoTitleBar); this.setOwnerActivity(AuthorizationRequest.this.activity); assert requestUri != null; this.requestUri = requestUri; } /** Called when the user hits the back button on the dialog. */ @Override public void onCancel(DialogInterface dialog) { LiveAuthException exception = new LiveAuthException(ErrorMessages.SIGNIN_CANCEL); AuthorizationRequest.this.onException(exception); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setOnCancelListener(this); FrameLayout content = new FrameLayout(this.getContext()); LinearLayout webViewContainer = new LinearLayout(this.getContext()); WebView webView = new WebView(this.getContext()); webView.setWebViewClient(new AuthorizationWebViewClient()); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadUrl(this.requestUri.toString()); webView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); webView.setVisibility(View.VISIBLE); webViewContainer.addView(webView); webViewContainer.setVisibility(View.VISIBLE); content.addView(webViewContainer); content.setVisibility(View.VISIBLE); content.forceLayout(); webViewContainer.forceLayout(); this.addContentView(content, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } } /** * Compares just the scheme, authority, and path. It does not compare the query parameters or * the fragment. */ private enum UriComparator implements Comparator<Uri> { INSTANCE; @Override public int compare(Uri lhs, Uri rhs) { String[] lhsParts = { lhs.getScheme(), lhs.getAuthority(), lhs.getPath() }; String[] rhsParts = { rhs.getScheme(), rhs.getAuthority(), rhs.getPath() }; assert lhsParts.length == rhsParts.length; for (int i = 0; i < lhsParts.length; i++) { int compare = lhsParts[i].compareTo(rhsParts[i]); if (compare != 0) { return compare; } } return 0; } } private static final String AMPERSAND = "&"; private static final String EQUALS = "="; /** * Turns the fragment parameters of the uri into a map. * * @param uri to get fragment parameters from * @return a map containing the fragment parameters */ private static Map<String, String> getFragmentParametersMap(Uri uri) { String fragment = uri.getFragment(); String[] keyValuePairs = TextUtils.split(fragment, AMPERSAND); Map<String, String> fragementParameters = new HashMap<String, String>(); for (String keyValuePair : keyValuePairs) { int index = keyValuePair.indexOf(EQUALS); String key = keyValuePair.substring(0, index); String value = keyValuePair.substring(index + 1); fragementParameters.put(key, value); } return fragementParameters; } private final Activity activity; private final HttpClient client; private final String clientId; private final DefaultObservableOAuthRequest observable; private final String redirectUri; private final String scope; public AuthorizationRequest(Activity activity, HttpClient client, String clientId, String redirectUri, String scope) { assert activity != null; assert client != null; assert !TextUtils.isEmpty(clientId); assert !TextUtils.isEmpty(redirectUri); assert !TextUtils.isEmpty(scope); this.activity = activity; this.client = client; this.clientId = clientId; this.redirectUri = redirectUri; this.observable = new DefaultObservableOAuthRequest(); this.scope = scope; } @Override public void addObserver(OAuthRequestObserver observer) { this.observable.addObserver(observer); } /** * Launches the login/consent page inside of a Dialog that contains a WebView and then performs * a AccessTokenRequest on successful login and consent. This method is async and will call the * passed in listener when it is completed. */ public void execute() { String displayType = this.getDisplayParameter(); String responseType = OAuth.ResponseType.CODE.toString().toLowerCase(Locale.US); String locale = Locale.getDefault().toString(); Uri requestUri = Config.INSTANCE.getOAuthAuthorizeUri() .buildUpon() .appendQueryParameter(OAuth.CLIENT_ID, this.clientId) .appendQueryParameter(OAuth.SCOPE, this.scope) .appendQueryParameter(OAuth.DISPLAY, displayType) .appendQueryParameter(OAuth.RESPONSE_TYPE, responseType) .appendQueryParameter(OAuth.LOCALE, locale) .appendQueryParameter(OAuth.REDIRECT_URI, this.redirectUri) .build(); OAuthDialog oAuthDialog = new OAuthDialog(requestUri); oAuthDialog.show(); } @Override public void onException(LiveAuthException exception) { this.observable.notifyObservers(exception); } @Override public void onResponse(OAuthResponse response) { this.observable.notifyObservers(response); } @Override public boolean removeObserver(OAuthRequestObserver observer) { return this.observable.removeObserver(observer); } /** * Gets the display parameter by looking at the screen size of the activity. * @return "android_phone" for phones and "android_tablet" for tablets. */ private String getDisplayParameter() { ScreenSize screenSize = ScreenSize.determineScreenSize(this.activity); DeviceType deviceType = screenSize.getDeviceType(); return deviceType.getDisplayParameter().toString().toLowerCase(Locale.US); } private void onAccessTokenResponse(Map<String, String> fragmentParameters) { assert fragmentParameters != null; OAuthSuccessfulResponse response; try { response = OAuthSuccessfulResponse.createFromFragment(fragmentParameters); } catch (LiveAuthException e) { this.onException(e); return; } this.onResponse(response); } private void onAuthorizationResponse(String code) { assert !TextUtils.isEmpty(code); // Since we DO have an authorization code, launch an AccessTokenRequest. // We do this asynchronously to prevent the HTTP IO from occupying the // UI/main thread (which we are on right now). AccessTokenRequest request = new AccessTokenRequest(this.client, this.clientId, this.redirectUri, code); TokenRequestAsync requestAsync = new TokenRequestAsync(request); // We want to know when this request finishes, because we need to notify our // observers. requestAsync.addObserver(this); requestAsync.execute(); } /** * Called when the end uri is loaded. * * This method will read the uri's query parameters and fragment, and respond with the * appropriate action. * * @param endUri that was loaded */ private void onEndUri(Uri endUri) { // If we are on an end uri, the response could either be in // the fragment or the query parameters. The response could // either be successful or it could contain an error. // Check all situations and call the listener's appropriate callback. // Callback the listener on the UI/main thread. We could call it right away since // we are on the UI/main thread, but it is probably better that we finish up with // the WebView code before we callback on the listener. boolean hasFragment = endUri.getFragment() != null; boolean hasQueryParameters = endUri.getQuery() != null; boolean invalidUri = !hasFragment && !hasQueryParameters; // check for an invalid uri, and leave early if (invalidUri) { this.onInvalidUri(); return; } if (hasFragment) { Map<String, String> fragmentParameters = AuthorizationRequest.getFragmentParametersMap(endUri); boolean isSuccessfulResponse = fragmentParameters.containsKey(OAuth.ACCESS_TOKEN) && fragmentParameters.containsKey(OAuth.TOKEN_TYPE); if (isSuccessfulResponse) { this.onAccessTokenResponse(fragmentParameters); return; } String error = fragmentParameters.get(OAuth.ERROR); if (error != null) { String errorDescription = fragmentParameters.get(OAuth.ERROR_DESCRIPTION); String errorUri = fragmentParameters.get(OAuth.ERROR_URI); this.onError(error, errorDescription, errorUri); return; } } if (hasQueryParameters) { String code = endUri.getQueryParameter(OAuth.CODE); if (code != null) { this.onAuthorizationResponse(code); return; } String error = endUri.getQueryParameter(OAuth.ERROR); if (error != null) { String errorDescription = endUri.getQueryParameter(OAuth.ERROR_DESCRIPTION); String errorUri = endUri.getQueryParameter(OAuth.ERROR_URI); this.onError(error, errorDescription, errorUri); return; } } // if the code reaches this point, the uri was invalid // because it did not contain either a successful response // or an error in either the queryParameter or the fragment this.onInvalidUri(); } /** * Called when end uri had an error in either the fragment or the query parameter. * * This method constructs the proper exception, calls the listener's appropriate callback method * on the main/UI thread, and then dismisses the dialog window. * * @param error containing an error code * @param errorDescription optional text with additional information * @param errorUri optional uri that is associated with the error. */ private void onError(String error, String errorDescription, String errorUri) { LiveAuthException exception = new LiveAuthException(error, errorDescription, errorUri); this.onException(exception); } /** * Called when an invalid uri (i.e., a uri that does not contain an error or a successful * response). * * This method constructs an exception, calls the listener's appropriate callback on the main/UI * thread, and then dismisses the dialog window. */ private void onInvalidUri() { LiveAuthException exception = new LiveAuthException(ErrorMessages.SERVER_ERROR); this.onException(exception); } }
package org.xins.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.Enumeration; import java.util.Properties; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.NullEnumeration; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.io.FileWatcher; import org.xins.util.servlet.ServletUtils; import org.xins.util.text.Replacer; /** * Servlet that forwards requests to an <code>API</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public final class APIServlet extends Object implements Servlet { // Class fields /** * The <em>uninitialized</em> state. See {@link #_state}. */ private static final State UNINITIALIZED = new State("UNINITIALIZED"); /** * The <em>initializing</em> state. See {@link #_state}. */ private static final State INITIALIZING = new State("INITIALIZING"); /** * The <em>ready</em> state. See {@link #_state}. */ private static final State READY = new State("READY"); /** * The <em>disposing</em> state. See {@link #_state}. */ private static final State DISPOSING = new State("DISPOSING"); /** * The <em>disposed</em> state. See {@link #_state}. */ private static final State DISPOSED = new State("DISPOSED"); /** * The name of the system property that specifies the location of the * configuration file. */ public static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config"; /** * The name of the initialization property that specifies the name of the * API class to load. */ public static final String API_CLASS_PROPERTY = "org.xins.api.class"; /** * The name of the configuration property that specifies the interval * for the configuration file modification checks, in seconds. */ public static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload"; /** * The default configuration file modification check interval, in seconds. */ public static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 60; // Class functions /** * Initializes an API instance based on the specified servlet * configuration. * * @param config * the servlet configuration, cannot be <code>null</code>. * * @throws ServletException * if an API instance could not be initialized. */ private static API configureAPI(ServletConfig config) throws ServletException { API api; // Determine the API class String apiClassName = config.getInitParameter(API_CLASS_PROPERTY); if (apiClassName == null || apiClassName.trim().length() < 1) { final String message = "Invalid application package. API class name not set in initialization parameter \"" + API_CLASS_PROPERTY + "\"."; Library.LIFESPAN_LOG.fatal(message); throw new ServletException(message); } // Load the API class Class apiClass; try { apiClass = Class.forName(apiClassName); } catch (Exception e) { String message = "Invalid application package. Failed to load API class set in initialization parameter \"" + API_CLASS_PROPERTY + "\": \"" + apiClassName + "\"."; Library.LIFESPAN_LOG.fatal(message, e); throw new ServletException(message); } // TODO: Check that the API class is derived from org.xins.server.API // Get the SINGLETON field Field singletonField; try { singletonField = apiClass.getDeclaredField("SINGLETON"); } catch (Exception e) { String message = "Invalid application package. Failed to lookup class field SINGLETON in API class \"" + apiClassName + "\"."; Library.LIFESPAN_LOG.fatal(message, e); throw new ServletException(message); } // Get the value of the SINGLETON field try { api = (API) singletonField.get(null); } catch (Exception e) { String message = "Invalid application package. Failed to get value of SINGLETON field of API class \"" + apiClassName + "\"."; Library.LIFESPAN_LOG.fatal(message, e); throw new ServletException(message); } // TODO: Make sure that the field is an instance of that same class if (Library.LIFESPAN_LOG.isDebugEnabled()) { Library.LIFESPAN_LOG.debug("Obtained API instance of class: \"" + apiClassName + "\"."); } // Initialize the API if (Library.LIFESPAN_LOG.isDebugEnabled()) { Library.LIFESPAN_LOG.debug("Initializing API."); } Properties settings = ServletUtils.settingsAsProperties(config); try { api.init(settings); } catch (Throwable e) { String message = "Failed to initialize API."; Library.LIFESPAN_LOG.fatal(message, e); // TODO: Let the API.init() rollback the initialization self try { api.destroy(); } catch (Throwable e2) { Library.LIFESPAN_LOG.error("Caught " + e2.getClass().getName() + " while destroying API instance of class " + api.getClass().getName() + ". Ignoring.", e2); } throw new ServletException(message); } if (Library.LIFESPAN_LOG.isDebugEnabled()) { Library.LIFESPAN_LOG.debug("Initialized API."); } return api; } // Constructors /** * Constructs a new <code>APIServlet</code> object. */ public APIServlet() { _stateLock = new Object(); _state = UNINITIALIZED; } // Fields /** * The current state. */ private State _state; /** * Lock for <code>_state</code> */ private Object _stateLock; /** * The stored servlet configuration object. */ private ServletConfig _servletConfig; /** * The name of the configuration file. */ private String _configFile; /** * The API that this servlet forwards requests to. */ private API _api; // Methods /** * Initializes this servlet using the specified configuration. The * (required) {@link ServletConfig} argument is stored internally and is * returned from {@link #getServletConfig()}. * * <p>The initialization procedure will take required information from 3 * sources, initially: * * <dl> * <dt><strong>1. Build-time settings</strong></dt> * <dd>The application package contains a <code>web.xml</code> file with * build-time settings. Some of these settings are required in order * for the XINS/Java Server Framework to start up, while others are * optional. These build-time settings are passed to the servlet by * the application server as a {@link ServletConfig} object. See * {@link #init(ServletConfig)}. * <br />The servlet configuration is the responsibility of the * <em>assembler</em>.</dd> * * <dt><strong>2. System properties</strong></dt> * <dd>The location of the configuration file must be passed to the * Java VM at startup, as a system property. * <br />System properties are the responsibility of the * <em>system administrator</em>. * <br />Example: * <br /><code>java -Dorg.xins.server.config=`pwd`/conf/xins.properties orion.jar</code></dd> * * <dt><strong>3. Configuration file</strong></dt> * <dd>The configuration file should contain runtime configuration * settings, like the settings for the logging subsystem. * <br />System properties are the responsibility of the * <em>system administrator</em>. * <br />Example contents for a configuration file: * <blockquote><code>log4j.rootLogger=DEBUG, console * <br />log4j.appender.console=org.apache.log4j.ConsoleAppender * <br />log4j.appender.console.layout=org.apache.log4j.PatternLayout * <br />log4j.appender.console.layout.ConversionPattern=%d %-5p [%c] %m%n</code></blockquote> * </dl> * * <p>The initialization is performed as follows: * * <ol> * <li>if this servlet is not currently <em>uninitialized</em>, then a * {@link ServletException} is thrown; this indicates a problem with * the application server; * <li>if <code>config</code> argument is <code>null</code> then a * {@link ServletException} is thrown; this indicates a problem * with the application server; * <li>the {@link ServletContext} is retrieved from the * {@link ServletConfig}, using the * {@link ServletConfig#getServletContext()} method; if the returned * value is <code>null</code>, then a {@link ServletException} is * thrown; this indicates a problem with the application server; * <li>the state is set to <em>initializing</em>; * <li>the value of the required system property named * {@link #CONFIG_FILE_SYSTEM_PROPERTY} is determined, this is the * relative or absolute path to the runtime configuration file; if * it is not set then a {@link ServletException} is thrown; * <li>the indicated configuration file is loaded and all * configuration properties in this file are read according to * {@link Properties#load(InputStream) the specifications for a property file}; * if this fails, then a {@link ServletException} is thrown; * <li>the logging subsystem is initialized using the properties from * the configuration file, see * {@link PropertyConfigurator#doConfigure(String,org.apache.log4j.spi.LoggerRepository) the Log4J documentation}; * <li>the logging system is investigated to check if it is properly * initialized, if it is not then apparently the configuration file * contained no initialization properties for it; in this case the * logging subsystem will be configured to log to the standard * output stream using a simple output method, with no log level * threshold and a warning message is immediately logged; * <li>at this point the logging subsystem is definitely initialized; * the interval for the configuration file modification checks is * determined by reading the * {@link #CONFIG_RELOAD_INTERVAL_PROPERTY} configuration property; * if this property is not set, then * {@link #DEFAULT_CONFIG_RELOAD_INTERVAL} is assumed; * if this property exists but has an invalid value, then a * <em>warning</em> message is logged and * {@link #DEFAULT_CONFIG_RELOAD_INTERVAL} is also assumed; * <li>the initialization property {@link #API_CLASS_PROPERTY} is read * from the {@link ServletConfig servlet configuration} (not from * the configuration file); if it is not set then a * {@link ServletException} is thrown. * <li>the API class, specified in the {@link #API_CLASS_PROPERTY} * property, is loaded; it must be derived from the {@link API} * class in the XINS/Java Server Framework; if this fails then a * {@link ServletException} is thrown; * <li>in the API class a static field called <code>SINGLETON</code> is * looked up and the value is determined; the value must be an * instance of that same class, and cannot be <code>null</code>; * if this fails, then a {@link ServletException} is thrown; * <li>the API instance will be initialized by calling * {@link API#init(Properties)}; if this fails a * {@link ServletException} is thrown; * <li>the {@link ServletConfig config} object is stored internally, to * be returned by {@link #getServletConfig()}. * <li>the state is set to <em>ready</em>. * <li>the configuration file watch thread is started; * </ol> * * <p>Note that if a {@link ServletException} is thrown, the state is reset * to <em>uninitialized</em>. * * <p>Also note that if the logging subsystem is already initialized and a * {@link ServletException} is thrown, a <em>fatal</em> message is logged * just before the exception is actually thrown. However, if the logging * subsystem is not yet initialized, then a message is printed to the * standard error stream. * * @param config * the {@link ServletConfig} object which contains initialization and * startup parameters for this servlet, as specified by the * <em>assembler</em>, cannot be <code>null</code>. * * @throws ServletException * if <code>config == null</code>, if this servlet is not uninitialized * or if the initialization failed for some other reason. */ public void init(ServletConfig config) throws ServletException { // Make sure the Library class is initialized String version = Library.getVersion(); // Hold the state lock synchronized (_stateLock) { // Check preconditions if (_state != UNINITIALIZED) { String message = "Application server malfunction detected. State is " + _state + " instead of " + UNINITIALIZED + '.'; Library.LIFESPAN_LOG.fatal(message); throw new ServletException(message); } else if (config == null) { String message = "Application server malfunction detected. No servlet configuration object passed."; Library.LIFESPAN_LOG.fatal(message); throw new ServletException(message); } // Get the ServletContext ServletContext context = config.getServletContext(); if (context == null) { String message = "Application server malfunction detected. No servlet context available."; Library.LIFESPAN_LOG.fatal(message); throw new ServletException(message); } // Check the implemented vs expected Java Servlet API version final int expectedMajor = 2; final int expectedMinor = 3; int major = context.getMajorVersion(); int minor = context.getMinorVersion(); if (major != expectedMajor || minor != expectedMinor) { Library.LIFESPAN_LOG.warn("Application server implements Java Servlet API version " + major + '.' + minor + " instead of the expected version " + expectedMajor + '.' + expectedMajor + ". The application may or may not work correctly."); } // Set the state _state = INITIALIZING; try { // Determine configuration file location _configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY); // Read properties from the config file if (_configFile == null || _configFile.length() < 1) { Library.LIFESPAN_LOG.error("System administration issue detected. System property \"" + CONFIG_FILE_SYSTEM_PROPERTY + "\" is not set."); } else { applyConfigFile(); } // Initialization starting Library.LIFESPAN_LOG.debug("XINS/Java Server Framework " + version + " is initializing."); // Initialize API instance _api = configureAPI(config); // Watch the configuration file if (_configFile != null) { FileWatcher.Listener listener = new ConfigurationFileListener(); final int delay = 10; // TODO: Read from config file FileWatcher watcher = new FileWatcher(_configFile, 10, listener); watcher.start(); Library.LIFESPAN_LOG.info("Using config file \"" + _configFile + "\". Checking for changes every " + delay + " seconds."); } // Initialization done Library.LIFESPAN_LOG.info("XINS/Java Server Framework " + version + " is initialized."); // Finally enter the ready state _state = READY; // Store the ServletConfig object, per the Servlet API Spec, see: // http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/Servlet.html#getServletConfig() _servletConfig = config; // If an exception is thrown, then reset the state } finally { if (_state != READY) { _state = UNINITIALIZED; } } } } private void applyConfigFile() { try { FileInputStream in = new FileInputStream(_configFile); Properties properties = new Properties(); properties.load(in); Library.configure(properties); } catch (FileNotFoundException exception) { Library.LIFESPAN_LOG.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened."); } catch (SecurityException exception) { Library.LIFESPAN_LOG.error("System administration issue detected. Access denied while loading configuration file \"" + _configFile + "\"."); } catch (IOException exception) { Library.LIFESPAN_LOG.error("System administration issue detected. Unable to read configuration file \"" + _configFile + "\"."); } } /** * Returns the <code>ServletConfig</code> object which contains the * initialization and startup parameters for this servlet. The returned * {@link ServletConfig} object is the one passed to the * {@link #init(ServletConfig)} method. * * @return * the {@link ServletConfig} object that was used to initialize this * servlet, not <code>null</code> if this servlet is indeed already * initialized. */ public ServletConfig getServletConfig() { return _servletConfig; } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Determine current time long start = System.currentTimeMillis(); // Check state if (_state != READY) { if (_state == UNINITIALIZED) { throw new ServletException("This servlet is not yet initialized."); } else if (_state == DISPOSING) { throw new ServletException("This servlet is currently being disposed."); } else if (_state == DISPOSED) { throw new ServletException("This servlet is disposed."); } else { throw new Error("This servlet is not ready, the state is unknown."); } } // TODO: Support and use OutputStream instead of Writer, for improved // performance // Call the API CallResult result = _api.handleCall(start, request); // Determine the XSLT to link to String xslt = request.getParameter("_xslt"); // Send the XML output to the stream and flush PrintWriter out = response.getWriter(); response.setContentType("text/xml"); CallResultOutputter.output(out, result, xslt); out.flush(); } /** * Returns information about this servlet, as plain text. * * @return * textual description of this servlet, not <code>null</code> and not an * empty character string. */ public String getServletInfo() { return "XINS " + Library.getVersion() + " API Servlet"; } public void destroy() { if (Library.LIFESPAN_LOG.isDebugEnabled()) { Library.LIFESPAN_LOG.debug("XINS/Java Server Framework shutdown initiated."); } synchronized (_stateLock) { _state = DISPOSING; if (_api != null) { _api.destroy(); } Library.LIFESPAN_LOG.info("XINS/Java Server Framework shutdown completed."); _state = DISPOSED; } } // Inner classes /** * State of an <code>APIServlet</code>. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.121 */ private static final class State extends Object { // Constructors private State(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); _name = name; } // Fields /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; // Methods /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ String getName() { return _name; } public String toString() { return _name; } } /** * Listener that reloads the configuration file if it changes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) * * @since XINS 0.121 */ private final class ConfigurationFileListener extends Object implements FileWatcher.Listener { // Constructors /** * Constructs a new <code>ConfigurationFileListener</code> object. */ private ConfigurationFileListener() { // empty } // Fields // Methods public void fileModified() { Library.LIFESPAN_LOG.info("Configuration file \"" + _configFile + "\" changed. Re-initializing XINS/Java Server Framework."); applyConfigFile(); // TODO: reinit API Library.LIFESPAN_LOG.info("Re-initialized XINS/Java Server Framework."); } public void fileNotFound() { Library.LIFESPAN_LOG.error("System administration issue detected. Configuration file \"" + _configFile + "\" cannot be opened."); } public void fileNotModified() { Library.LIFESPAN_LOG.debug("Configuration file \"" + _configFile + "\" is not modified."); } public void securityException(SecurityException exception) { Library.LIFESPAN_LOG.error("System administration issue detected. Access denied while reading file \"" + _configFile + "\"."); } } }
// Vilya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.whirled.server; import com.threerings.util.Name; import com.threerings.presents.net.AuthRequest; import com.threerings.presents.server.ClientFactory; import com.threerings.presents.server.ClientResolver; import com.threerings.presents.server.PresentsClient; import com.threerings.crowd.server.CrowdServer; import com.threerings.whirled.Log; import com.threerings.whirled.server.persist.SceneRepository; import com.threerings.whirled.util.SceneFactory; /** * The Whirled server extends the {@link CrowdServer} and provides access to managers and the like * that are needed by the Whirled serviecs. */ public abstract class WhirledServer extends CrowdServer { /** The scene registry. */ public static SceneRegistry screg; /** * Initializes all of the server services and prepares for operation. */ public void init () throws Exception { // do the base server initialization super.init(); // configure the client to use our whirled client clmgr.setClientFactory(new ClientFactory() { public PresentsClient createClient (AuthRequest areq) { return new WhirledClient(); } public ClientResolver createClientResolver (Name username) { return new ClientResolver(); } }); // create our scene registry screg = createSceneRegistry(); Log.info("Whirled server initialized."); } /** * Creates the scene registry to be used on this server. */ protected abstract SceneRegistry createSceneRegistry () throws Exception; }
package fr.paris.lutece.portal.service.init; /** * this class provides informations about application version */ public final class AppInfo { /** Defines the current version of the application */ private static final String APP_VERSION = "7.0.0-SNAPSHOT"; static final String LUTECE_BANNER_VERSION = "\n _ _ _ _____ ___ ___ ___ ____\n" + "| | | | | | |_ _| | __| / __| | __| |__ |\n" + "| |__ | |_| | | | | _| | (__ | _| / / \n" + "|____| \\___/ |_| |___| \\___| |___| /_/ "; static final String LUTECE_BANNER_SERVER = "\n _ _ _ _____ ___ ___ ___ ___ ___ ___ __ __ ___ ___ \n" + "| | | | | | |_ _| | __| / __| | __| / __| | __| | _ \\ \\ \\ / / | __| | _ \\\n" + "| |__ | |_| | | | | _| | (__ | _| \\__ \\ | _| | / \\ V / | _| | /\n" + "|____| \\___/ |_| |___| \\___| |___| |___/ |___| |_|_\\ \\_/ |___| |_|_\\"; /** * Creates a new AppInfo object. */ private AppInfo( ) { } /** * Returns the current version of the application * * @return APP_VERSION The current version of the application */ public static String getVersion( ) { return APP_VERSION; } }
package org.apache.commons.collections; import java.io.IOException; import java.io.ObjectInputStream; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; public class MultiHashMap extends HashMap implements MultiMap { //backed values collection private transient Collection values = null; // compatibility with commons-collection releases 2.0/2.1 private static final long serialVersionUID = 1943563828307035349L; /** * Constructor. */ public MultiHashMap() { super(); } /** * Constructor. * * @param initialCapacity the initial map capacity */ public MultiHashMap(int initialCapacity) { super(initialCapacity); } /** * Constructor. * * @param initialCapacity the initial map capacity * @param loadFactor the amount 0.0-1.0 at which to resize the map */ public MultiHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } /** * Constructor. * * @param mapToCopy a Map to copy */ public MultiHashMap(Map mapToCopy) { super(mapToCopy); } /** * Read the object during deserialization. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { // This method is needed because the 1.2/1.3 Java deserialisation called // put and thus messed up that method // default read object s.defaultReadObject(); // problem only with jvm <1.4 String version = "1.2"; try { version = System.getProperty("java.version"); } catch (SecurityException ex) { // ignore and treat as 1.2/1.3 } if (version.startsWith("1.2") || version.startsWith("1.3")) { for (Iterator iterator = entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); // put has created a extra collection level, remove it super.put(entry.getKey(), ((Collection) entry.getValue()).iterator().next()); } } } /** * Put a key and value into the map. * <p> * The value is added to a collection mapped to the key instead of * replacing the previous value. * * @param key the key to set * @param value the value to set the key to * @return the value added if the add is successful, <code>null</code> otherwise */ public Object put(Object key, Object value) { // NOTE:: put is called during deserialization in JDK < 1.4 !!!!!! // so we must have a readObject() Collection coll = (Collection) super.get(key); if (coll == null) { coll = createCollection(null); super.put(key, coll); } boolean results = coll.add(value); return (results ? value : null); } /** * Does the map contain a specific value. * <p> * This searches the collection mapped to each key, and thus could be slow. * * @param value the value to search for * @return true if the list contains the value */ public boolean containsValue(Object value) { Set pairs = super.entrySet(); if (pairs == null) { return false; } Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); if (coll.contains(value)) { return true; } } return false; } /** * Removes a specific value from map. * <p> * The item is removed from the collection mapped to the specified key. * * @param key the key to remove from * @param value the value to remove * @return the value removed (which was passed in) */ public Object remove(Object key, Object item) { Collection valuesForKey = (Collection) super.get(key); if (valuesForKey == null) { return null; } valuesForKey.remove(item); // remove the list if it is now empty // (saves space, and allows equals to work) if (valuesForKey.isEmpty()){ remove(key); } return item; } /** * Clear the map. * <p> * This clears each collection in the map, and so may be slow. */ public void clear() { // For gc, clear each list in the map Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while (pairsIterator.hasNext()) { Map.Entry keyValuePair = (Map.Entry) pairsIterator.next(); Collection coll = (Collection) keyValuePair.getValue(); coll.clear(); } super.clear(); } /** * Gets a view over all the values in the map. * <p> * The values view includes all the entries in the collections at each map key. * * @return the collection view of all the values in the map */ public Collection values() { Collection vs = values; return (vs != null ? vs : (values = new Values())); } /** * Inner class to view the elements. */ private class Values extends AbstractCollection { public Iterator iterator() { return new ValueIterator(); } public int size() { int compt = 0; Iterator it = iterator(); while (it.hasNext()) { it.next(); compt++; } return compt; } public void clear() { MultiHashMap.this.clear(); } } /** * Inner iterator to view the elements. */ private class ValueIterator implements Iterator { private Iterator backedIterator; private Iterator tempIterator; private ValueIterator() { backedIterator = MultiHashMap.super.values().iterator(); } private boolean searchNextIterator() { while (tempIterator == null || tempIterator.hasNext() == false) { if (backedIterator.hasNext() == false) { return false; } tempIterator = ((Collection) backedIterator.next()).iterator(); } return true; } public boolean hasNext() { return searchNextIterator(); } public Object next() { if (searchNextIterator() == false) { throw new NoSuchElementException(); } return tempIterator.next(); } public void remove() { if (tempIterator == null) { throw new IllegalStateException(); } tempIterator.remove(); } } /** * Clone the map. * <p> * The clone will shallow clone the collections as well as the map. * * @return the cloned map */ public Object clone() { MultiHashMap obj = (MultiHashMap) super.clone(); // clone each Collection container for (Iterator it = entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); Collection coll = (Collection) entry.getValue(); Collection newColl = createCollection(coll); entry.setValue(newColl); } return obj; } /** * Creates a new instance of the map value Collection container. * <p> * This method can be overridden to use your own collection type. * * @param coll the collection to copy, may be null * @return the new collection */ protected Collection createCollection(Collection coll) { if (coll == null) { return new ArrayList(); } else { return new ArrayList(coll); } } }
package org.apache.velocity.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletResponse; import org.apache.velocity.Template; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.io.VelocityWriter; import org.apache.velocity.util.SimplePool; import org.apache.velocity.context.Context; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.HttpServletRequestWrap; import org.apache.velocity.app.HttpServletResponseWrap; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.MethodInvocationException; /** * Base class which simplifies the use of Velocity with Servlets. * Extend this class, implement the <code>handleRequest()</code> method, * and add your data to the context. Then call * <code>getTemplate("myTemplate.wm")</code>. * * This class puts some things into the context object that you should * be aware of: * <pre> * "req" - The HttpServletRequest object * "res" - The HttpServletResponse object * </pre> * * There are other methods you can override to access, alter or control * any part of the request processing chain. Please see the javadocs for * more information on : * <ul> * <li> loadConfiguration() : for setting up the Velocity runtime * <li> createContext() : for creating and loading the Context * <li> setContentType() : for changing the content type on a request * by request basis * <li> handleRequest() : you <b>must</b> implement this * <li> mergeTemplate() : the template rendering process * <li> requestCleanup() : post rendering resource or other cleanup * <li> error() : error handling * </ul> * <br> * If you put a contentType object into the context within either your * serlvet or within your template, then that will be used to override * the default content type specified in the properties file. * * "contentType" - The value for the Content-Type: header * * @author Dave Bryson * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @author <a href="kjohnson@transparent.com">Kent Johnson</a> * $Id: VelocityServlet.java,v 1.33 2001/05/10 01:12:10 geirm Exp $ */ public abstract class VelocityServlet extends HttpServlet { /** * The HTTP request object context key. */ public static final String REQUEST = "req"; /** * The HTTP response object context key. */ public static final String RESPONSE = "res"; /** * The HTTP content type context key. */ public static final String CONTENT_TYPE = "default.contentType"; /** * The default content type for the response */ public static final String DEFAULT_CONTENT_TYPE = "text/html"; /** * Encoding for the output stream */ public static final String DEFAULT_OUTPUT_ENCODING = "ISO-8859-1"; /** * The encoding to use when generating outputing. */ private static String encoding = null; /** * The default content type. */ private static String defaultContentType; /** * This is the string that is looked for when getInitParameter is * called. */ private static final String INIT_PROPS_KEY = "properties"; /** * Cache of writers */ private static SimplePool writerPool = new SimplePool(40); /** * Performs initialization of this servlet. Called by the servlet * container on loading. * * @param config The servlet configuration to apply. * * @exception ServletException */ public void init( ServletConfig config ) throws ServletException { super.init( config ); try { /* * call the overridable method to allow the * derived classes a shot at altering the configuration * before initializing Runtime */ Properties props = loadConfiguration( config ); Velocity.init( props ); defaultContentType = Runtime.getString( CONTENT_TYPE, DEFAULT_CONTENT_TYPE); encoding = Runtime.getString( Runtime.OUTPUT_ENCODING, DEFAULT_OUTPUT_ENCODING); } catch( Exception e ) { throw new ServletException("Error configuring the loader: " + e); } } /** * Loads the configuration information and returns that * information as a Properties, which will be used to * initialize the Velocity runtime. * <br><br> * Currently, this method gets the initialization parameter * VelocityServlet.INIT_PROPS_KEY, which should be a file containing * the configuration information. * <br><br> * To configure your Servlet Spec 2.2 compliant servlet runner to pass this * to you, put the following in your WEB-INF/web.xml file * <br> * <pre> * &lt;servlet &gt; * &lt;servlet-name&gt; YourServlet &lt/servlet-name&gt; * &lt;servlet-class&gt; your.package.YourServlet &lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt; properties &lt;/param-name&gt; * &lt;param-value&gt; velocity.properties &lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * </pre> * * Derived classes may do the same, or take advantage of this code to do the loading for them via : * <pre> * Properties p = super.loadConfiguration( config ); * </pre> * and then add or modify the configuration values from the file. * <br> * * @param config ServletConfig passed to the servlets init() function * Can be used to access the real path via ServletContext (hint) * @return java.util.Properties loaded with configuration values to be used * to initialize the Velocity runtime. * @throws FileNotFoundException if a specified file is not found. * @throws IOException I/O problem accessing the specified file, if specified. */ protected Properties loadConfiguration(ServletConfig config ) throws IOException, FileNotFoundException { String propsFile = config.getInitParameter(INIT_PROPS_KEY); /* * This will attempt to find the location of the properties * file from the relative path to the WAR archive (ie: * docroot). Since JServ returns null for getRealPath() * because it was never implemented correctly, then we know we * will not have an issue with using it this way. I don't know * if this will break other servlet engines, but it probably * shouldn't since WAR files are the future anyways. */ Properties p = new Properties(); if ( propsFile != null ) { String realPath = getServletContext().getRealPath(propsFile); if ( realPath != null ) { propsFile = realPath; } p.load( new FileInputStream(propsFile) ); } return p; } /** * Handles GET - calls doRequest() */ public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handle a POST request - calls doRequest() */ public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doRequest(request, response); } /** * Handles all requests * * @param request HttpServletRequest object containing client request * @param response HttpServletResponse object for the response */ protected void doRequest(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { try { /* * first, get a context */ Context context = createContext( request, response ); /* * set the content type */ setContentType( request, response ); /* * let someone handle the request */ Template template = handleRequest( request, response, context ); /* * bail if we can't find the template */ if ( template == null ) { return; } /* * now merge it */ mergeTemplate( template, context, response ); /* * call cleanup routine to let a derived class do some cleanup */ requestCleanup( request, response, context ); } catch (Exception e) { /* * call the error handler to let the derived class * do something useful with this failure. */ error( request, response, e); } } protected void requestCleanup( HttpServletRequest request, HttpServletResponse response, Context context ) { return; } protected void mergeTemplate( Template template, Context context, HttpServletResponse response ) throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, IOException, UnsupportedEncodingException, Exception { ServletOutputStream output = response.getOutputStream(); VelocityWriter vw = null; try { vw = (VelocityWriter) writerPool.get(); if (vw == null) { vw = new VelocityWriter( new OutputStreamWriter(output, encoding), 4*1024, true); } else { vw.recycle(new OutputStreamWriter(output, encoding)); } template.merge( context, vw); } finally { try { if (vw != null) { /* * we just put the VelWriter back into the * pool. We don't even have to flush. * and we certainly shouldn't close it */ writerPool.put(vw); } } catch (Exception e) { // do nothing } } } /** * Sets the content type of the response. This is available to be overriden * by a derived class. * * The default implementation is : * * response.setContentType( defaultContentType ); * * where defaultContentType is set to the value of the default.contentType * property, or "text/html" if that is not set. * * @param request servlet request from client * @param response servlet reponse to client */ protected void setContentType( HttpServletRequest request, HttpServletResponse response ) { response.setContentType( defaultContentType ); } /** * Returns a context suitable to pass to the handleRequest() method * <br><br> * Default implementation will create a VelocityContext object, * put the HttpServletRequest and HttpServletResponse * into the context accessable via the keys VelocityServlet.REQUEST and * VelocityServlet.RESPONSE, respectively. * * @param request servlet request from client * @param response servlet reponse to client * * @return context */ protected Context createContext(HttpServletRequest request, HttpServletResponse response ) { /* * create a new context */ VelocityContext context = new VelocityContext(); /* * put the request/response objects into the context * wrap the HttpServletRequest to solve the introspection * problems */ context.put( REQUEST, new HttpServletRequestWrap( request ) ); context.put( RESPONSE, new HttpServletResponseWrap( response ) ); return context; } /** * Retrieves the requested template. * * @param name The file name of the template to retrieve relative to the * template root. * @return The requested template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public Template getTemplate( String name ) throws ResourceNotFoundException, ParseErrorException, Exception { return Runtime.getTemplate(name); } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may handle the request directly * and return <code>null</code> or throw a more meaningful exception * for the error handler to catch. * * @param request servlet request from client * @param response servlet reponse * @param ctx The context to add your data to. * @return The template to merge with your context or null, indicating * that you handled the processing. */ protected Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx ) throws Exception { /* * invoke handleRequest */ Template t = handleRequest( ctx ); /* * if it returns null, this is the 'old' deprecated * way, and we want to mimic the behavior for a little * while anyway */ if (t == null) { throw new Exception ("handleRequest(Context) returned null - no template selected!" ); } return t; } /** * Implement this method to add your application data to the context, * calling the <code>getTemplate()</code> method to produce your return * value. * <br><br> * In the event of a problem, you may simple return <code>null</code> * or throw a more meaningful exception. * * @deprecated Use * {@link #handleRequest( HttpServletRequest request, * HttpServletResponse response, Context ctx )} * * @param ctx The context to add your data to. * @return The template to merge with your context. */ protected Template handleRequest( Context ctx ) throws Exception { throw new Exception ("You must override VelocityServlet.handleRequest( Context) " + " or VelocityServlet.handleRequest( HttpServletRequest, " + " HttpServletResponse, Context)" ); } /** * Invoked when there is an error thrown in any part of doRequest() processing. * <br><br> * Default will send a simple HTML response indicating there was a problem. * * @param request original HttpServletRequest from servlet container. * @param response HttpServletResponse object from servlet container. * @param cause Exception that was thrown by some other part of process. */ protected void error( HttpServletRequest request, HttpServletResponse response, Exception cause ) throws ServletException, IOException { StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<body bgcolor=\"#ffffff\">"); html.append("<h2>VelocityServlet : Error processing the template</h2>"); html.append( cause ); html.append("<br>"); StringWriter sw = new StringWriter(); cause.printStackTrace( new PrintWriter( sw ) ); html.append( sw.toString() ); html.append("</body>"); html.append("</html>"); response.getOutputStream().print( html.toString() ); } }
package com.trendrr.oss.taskprocessor; import java.util.Comparator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.trendrr.oss.FileCache; import com.trendrr.oss.PriorityUpdateQueue; import com.trendrr.oss.concurrent.LazyInitObject; import com.trendrr.oss.executionreport.ExecutionReport; import com.trendrr.oss.executionreport.ExecutionReportIncrementor; import com.trendrr.oss.executionreport.ExecutionSubReport; import com.trendrr.oss.taskprocessor.Task.ASYNCH; /** * @author Dustin Norlander * @created Sep 24, 2012 * */ public class TaskProcessor { protected static Log log = LogFactory.getLog(TaskProcessor.class); static class TaskProcessorThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; TaskProcessorThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); group = (s != null)? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "TP-" + name +"-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } static LazyInitObject<AsynchTaskRegistery> asynchTasks = new LazyInitObject<AsynchTaskRegistery>() { @Override public AsynchTaskRegistery init() { AsynchTaskRegistery reg = new AsynchTaskRegistery(); reg.start(); return reg; } }; protected ExecutorService threadPool = null; protected String name; protected TaskCallback callback; //example threadpool, blocks when queue is full. // ExecutorService threadPool = new ThreadPoolExecutor( // 1, // core size // 30, // max size // 130, // idle timeout // TimeUnit.SECONDS, // new ArrayBlockingQueue<Runnable>(30), // queue with a size // new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. /** * creates a new TaskProcessor with a new executorService * ExecutorService threadPool = new ThreadPoolExecutor( 1, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); * * @param name * @param callback * @param numThreads */ public static TaskProcessor defaultInstance(String name, TaskCallback callback, int numThreads) { ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 1, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new TaskProcessorThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); return new TaskProcessor(name, callback, threadPool); } /** * creates a new task processor. * * * * * @param name The name of this processor. used for execution reporting. * @param callback Methods called for every task execution. this callback is called before the callback specified in the task. can be null. * @param executor the executor */ public TaskProcessor(String name, TaskCallback callback, ExecutorService executor) { this.threadPool = executor; this.name = name; this.callback = callback; } /** * submits a task for execution. * @param task */ public void submitTask(Task task) { if (task.getSubmitted() == null) { task.submitted(); } task.setProcessor(this); //add to the executor service.. TaskFilterRunner runner = new TaskFilterRunner(task); this.threadPool.execute(runner); } public void setAsynch(Task t, ASYNCH asynch, long timeout) { asynchTasks.get().add(t, asynch, timeout); } /** * submit a future, a separate thread will poll it on interval and * call your callback when isDone is set, or cancel once the timeout has. * * callback is executed in one of this processors executor threads. * @param future * @param callback */ public void submitFuture(Task task, Future future, FuturePollerCallback callback, long timeout) { FuturePollerWrapper wrapper = new FuturePollerWrapper(future, callback, timeout, task); asynchTasks.get().addFuture(wrapper); } public void resumeAsynch(String taskId) { asynchTasks.get().resume(taskId); } public ExecutorService getExecutor() { return this.threadPool; } /** * A unique name for this processor. only one instance per name will be allowed. * @return */ public String getName() { return this.name; } public void taskComplete(Task task) { if (this.callback != null) { this.callback.taskComplete(task); } if (task.getCallback() != null) { task.getCallback().taskComplete(task); } } public void taskError(Task task, Exception error) { if (this.callback != null) { this.callback.taskError(task, error); } if (task.getCallback() != null) { task.getCallback().taskError(task, error); } } /** * gets the execution report incrementor for TaskProcessor.{this.getName} * * @return */ public ExecutionReportIncrementor getExecutionReport() { return new ExecutionSubReport(this.getName(), ExecutionReport.instance("TaskProcessor")); } }
/** This package handles all db cruds First note that all the stateless beans were made as granular as possible so that, in the event of a large system taking up a lot of memory, services can be fine tuned. This approach was taken against one huge service class to do this optimization later. How ever, fine grained control on stateless beans are yet to be supported by vendors. Following content is rather old and out dated Following content is NOT outdated as reviewed on 2011/09/24 C = Create R = Read U = Update D = Delete, Public classes here are always one entity handling another. For example A creates B, so the class ACB is public. The rest of the classes are visible only to the package., CrudService in injected only to the package visible only classes. In most cases, there are pure entity handles. i.e. NOT one entity handling a nother., CrudService never creates a transaction. It SUPPORTS and MANDATORY. Hence the callers should handle the transactions. The classes containing CrudService always ENFORCE a transaction level. i.e. REQUIRES_NEW(NTxR), NOT_SUPPORTED(DirtyR), REQUIRED(R) Others always define a transaction level, REQUIRES_NEW(NTxR), NOT_SUPPORTED(DirtyR), REQUIRED(R) Please note that each one of these will have a separate method such as doC[type], doDirtyC[type], doNTxC[type] where NTx stands for transactional(meaning do it in a new transaction). Always remember that database cleanliness(handling null fields) is done by classes containing CrudService, Map MANDATORY->REQUIRES_NEW,MANDATORY SUPPORTS->ALL, As C=Create R=Read U=Update D=Delete Implies the operation, instead of saying set or get, we say do. For Example, doEntity1UEntityB, which implies \Do Entity 1 Update Entity2., The private classes show attitude \I don't care who calls me, as long as I can work on the database to make a consistant crud without leading to stale data\. The public classes show attitude \I do care who calls me. I will make sure this guy can really do this operation, and if he sends me the correct data\., There should not be any exception thrown in this package which are conflicts in database. Each logic should be checked and handle here regardless of if the caller does it. Therefore, if the caller makes a mistake, the exception thrown to him should be a tailor-made one, where as the error should NOT execute. Is simple words, no operation can break the database by calling any class in this package!, In simple words, CrudService is flexible in transaction scope and never creates one.(MANDATORY(mostly create operations), SUPPORTS) Classes containing CrudService(unit classes), enforce database atomicity. Hence enforce transactional scopes(NOT_SUPPORTED(implying to the caller it is non TX), REQUIRED, REQUIRES_NEW)}) **/
package at.favre.tools.converter; import at.favre.tools.converter.arg.ECompression; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; import javax.imageio.stream.ImageOutputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Util class */ public class ConverterUtil { public static String getWithoutExtension(File file) { String fileName = file.getName(); int pos = fileName.lastIndexOf("."); if (pos > 0) { fileName = fileName.substring(0, pos); } return fileName; } public static String getFileExtension(File file) { return file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase(); } public static File createAndCheckFolder(String path) { File f = new File(path); if (!f.exists()) { f.mkdir(); } if (!f.exists() || !f.isDirectory()) { throw new IllegalStateException("could not create folder: " + path); } return f; } public static BufferedImage loadImage(String filePath) throws Exception { return ImageIO.read(new File(filePath)); } public static List<File> compressToFile(File targetFile, List<ECompression> compressionList, BufferedImage bufferedImage, Dimension targetDimension, float compressionQuality, boolean skipIfExists) throws Exception { List<File> files = new ArrayList<>(2); for (ECompression compression : compressionList) { File imageFile = new File(targetFile.getAbsolutePath() + "." + compression.name().toLowerCase()); if (imageFile.exists() && skipIfExists) { break; } if (compression == ECompression.PNG || compression == ECompression.GIF) { ImageIO.write(scale(bufferedImage, targetDimension.width, targetDimension.height, compression, Color.BLACK), compression.name().toLowerCase(), imageFile); } else if (compression == ECompression.JPG) { compressJpeg(imageFile, scale(bufferedImage, targetDimension.width, targetDimension.height, compression, Color.BLACK), compressionQuality); } files.add(imageFile); } return files; } public static void compressJpeg(File targetFile,BufferedImage bufferedImage, float quality) throws IOException { ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next(); ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam(); jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); jpgWriteParam.setCompressionQuality(quality); ImageWriter writer = null; try (ImageOutputStream outputStream = new FileImageOutputStream(targetFile)) { writer = ImageIO.getImageWritersByFormatName("jpg").next(); writer.setOutput(outputStream); writer.write(null, new IIOImage(bufferedImage, null, null), jpgWriteParam); } finally { if (writer != null) writer.dispose(); } } public static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, ECompression compression, Color background) { BufferedImage scaledImage = null; if (imageToScale != null) { int imageType = imageToScale.getType(); if (compression == ECompression.PNG || compression == ECompression.GIF) { imageType = BufferedImage.TYPE_INT_ARGB; } scaledImage = new BufferedImage(dWidth, dHeight, imageType); Graphics2D graphics2D = scaledImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics2D.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (compression == ECompression.JPG) { graphics2D.drawImage(imageToScale, 0, 0, dWidth, dHeight, null); } else { graphics2D.drawImage(imageToScale, 0, 0, dWidth, dHeight, null); } graphics2D.dispose(); } return scaledImage; } }
package br.com.dbsoft.ui.bean.crud; import java.lang.annotation.Annotation; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.enterprise.context.Conversation; import javax.enterprise.context.ConversationScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.dbsoft.core.DBSApproval; import br.com.dbsoft.core.DBSApproval.APPROVAL_STAGE; import br.com.dbsoft.core.DBSSDK; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.io.DBSColumn; import br.com.dbsoft.io.DBSDAO; import br.com.dbsoft.io.DBSResultDataModel; import br.com.dbsoft.message.DBSMessage; import br.com.dbsoft.message.IDBSMessage; import br.com.dbsoft.message.IDBSMessage.MESSAGE_TYPE; import br.com.dbsoft.ui.bean.DBSBeanModalMessages; import br.com.dbsoft.ui.bean.crud.DBSCrudBeanEvent.CRUD_EVENT; import br.com.dbsoft.ui.component.DBSUIInput; import br.com.dbsoft.ui.component.DBSUIInputText; import br.com.dbsoft.ui.component.modalcrudmessages.IDBSModalCrudMessages; import br.com.dbsoft.ui.core.DBSFaces; import br.com.dbsoft.util.DBSDate; import br.com.dbsoft.util.DBSIO; import br.com.dbsoft.util.DBSNumber; import br.com.dbsoft.util.DBSObject; import br.com.dbsoft.util.DBSIO.SORT_DIRECTION; public abstract class DBSCrudBean extends DBSBeanModalMessages implements IDBSModalCrudMessages{ private static final long serialVersionUID = -8550893738791483527L; public static enum FormStyle { DIALOG (0), TABLE (1), VIEW (2); private int wCode; private FormStyle(int pCode) { this.wCode = pCode; } public int getCode() { return wCode; } public static FormStyle get(int pCode) { switch (pCode) { case 0: return DIALOG; case 1: return TABLE; case 2: return VIEW; default: return DIALOG; } } } public static enum EditingMode { NONE ("Not Editing", 0), INSERTING ("Inserting", 1), UPDATING ("Updating", 2), DELETING ("Deleting", 3), APPROVING ("Approving", 4), REPROVING ("Reproving", 5); private String wName; private int wCode; private EditingMode(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingMode get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return INSERTING; case 2: return UPDATING; case 3: return DELETING; case 4: return APPROVING; case 5: return REPROVING; default: return NONE; } } } public static enum EditingStage{ NONE ("None", 0), COMMITTING ("Committing", 1), IGNORING ("Ignoring", 2); private String wName; private int wCode; private EditingStage(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingStage get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return COMMITTING; case 2: return IGNORING; default: return NONE; } } } @Inject private Conversation wConversation; private static final long wConversationTimeout = 600000; //10 minutos protected DBSDAO<?> wDAO; private List<IDBSCrudBeanEventsListener> wEventListeners = new ArrayList<IDBSCrudBeanEventsListener>(); private EditingMode wEditingMode = EditingMode.NONE; private EditingStage wEditingStage = EditingStage.NONE; private FormStyle wFormStyle = FormStyle.DIALOG; private List<Integer> wSelectedRowsIndexes = new ArrayList<Integer>(); private Collection<DBSColumn> wSavedCurrentColumns = null; private boolean wValueChanged; private int wCopiedRowIndex = -1; private boolean wValidateComponentHasError = false; private Boolean wDialogOpened = false; private String wDialogCaption; private Boolean wDialogCloseAfterInsert = false; private String wMessageConfirmationEdit = "Confirmar a edição?"; private String wMessageConfirmationInsert = "Confirmar a inclusão?"; private String wMessageConfirmationDelete = "Confirmar a exclusão?"; private String wMessageConfirmationApprove = "Confirmar a aprovação?"; private String wMessageConfirmationReprove = "Confirmar a reprovação?"; private String wMessageIgnoreEdit = "Ignorar a edição?"; private String wMessageIgnoreInsert = "Ignorar a inclusão?"; private String wMessageIgnoreDelete = "Ignorar a exclusão?"; private Boolean wAllowUpdate = true; private Boolean wAllowInsert = true; private Boolean wAllowDelete = true; private Boolean wAllowRefresh = true; private Boolean wAllowApproval = false; private Boolean wAllowApprove = true; private Boolean wAllowReprove = true; private Boolean wAllowCopy = true; private Boolean wAllowCopyOnUpdate = false; private Integer wApprovalUserStages = 0; private String wColumnNameApprovalStage = null; private String wColumnNameApprovalUserIdRegistered = null; private String wColumnNameApprovalUserIdVerified = null; private String wColumnNameApprovalUserIdConferred = null; private String wColumnNameApprovalUserIdApproved = null; private String wColumnNameApprovalDateApproved = null; private String wColumnNameDateOnInsert = null; private String wColumnNameDateOnUpdate = null; private String wColumnNameUserIdOnInsert = null; private String wColumnNameUserIdOnUpdate = null; private String wSortColumn = ""; private String wSortDirection = SORT_DIRECTION.DESCENDING.getCode(); private Boolean wRevalidateBeforeCommit = false; private Integer wUserId; private Boolean wMultipleSelection = false; private DBSCrudBean wParentCrudBean = null; private List<DBSCrudBean> wChildrenCrudBean = new ArrayList<DBSCrudBean>(); //Mensagens private IDBSMessage wMessageNoRowComitted = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.noRowComitted")); private IDBSMessage wMessageOverSize = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.overSize")); private IDBSMessage wMessageNoChange = new DBSMessage(MESSAGE_TYPE.INFORMATION, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.noChange")); private IDBSMessage wMessaggeApprovalSameUser = new DBSMessage(MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvalSameUser")); public String getCID(){ return wConversation.getId(); } public void conversationBegin(){ for (Annotation xAnnotation:this.getClass().getDeclaredAnnotations()){ if (xAnnotation.annotationType() == ConversationScoped.class){ pvConversationBegin(); break; } } } @Override protected void initializeClass() { conversationBegin(); pvFireEventInitialize(); //Finaliza os outros crudbeans antes de inicializar este. // DBSFaces.finalizeDBSBeans(this, false); << Comentado pois os beans passaram a ser criados como ConversationScoped - 12/Ago/2014 } @Override protected void finalizeClass(){ pvFireEventFinalize(); //Exclui os listeners associadao, antes de finalizar wEventListeners.clear(); } public void addEventListener(IDBSCrudBeanEventsListener pEventListener) { if (!wEventListeners.contains(pEventListener)){ wEventListeners.add(pEventListener); } } public void removeEventListener(IDBSCrudBeanEventsListener pEventListener) { if (wEventListeners.contains(pEventListener)){ wEventListeners.remove(pEventListener); } } public <T> void setValue(String pColumnName, Object pColumnValue, Class<T> pValueClass){ T xValue = DBSObject.<T>toClassValue(pColumnValue, pValueClass); setValue(pColumnName, xValue); } public void setValue(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ setListValue(pColumnName, pColumnValue); }else{ pvSetValueDAO(pColumnName, pColumnValue); } } public <T> T getValue(String pColumnName){ //Utiliza ListValue para controlar os valores de todas as linhas if (wFormStyle == FormStyle.TABLE){ return getListValue(pColumnName); }else{ return pvGetValue(pColumnName); } } public <T> T getValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValue(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getValueOriginal(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValueOriginal(pColumnName); }else{ return null; } } public <T> T getValueOriginal(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getValueOriginal(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getListValue(String pColumnName){ if (wDAO != null){ return (T) wDAO.getListValue(pColumnName); }else{ return null; } } public <T> T getListValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClassValue(getListValue(pColumnName), pValueClass); } private void setListValue(String pColumnName, Object pColumnValue){ if (wDAO != null){ wDAO.setListValue(pColumnName, pColumnValue); } } public boolean getIsListNewRow(){ if (wDAO != null){ return wDAO.getIsNewRow(); }else{ return false; } } public String getListFormattedValue(String pColumnId) throws DBSIOException{return "pColumnId '" + pColumnId + "' desconhecida";} public IDBSMessage getColumnMessage(String pColumnName){ if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return wDAO.getMessage(pColumnName); }else{ return null; } } public void crudFormBeforeShowComponent(UIComponent pComponent){ if (wDAO!=null){ //Configura os campos do tipo input if (pComponent instanceof DBSUIInput){ DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) pComponent); if (xColumn!=null){ if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; xInput.setMaxLength(xColumn.getSize()); } } } } } public void crudFormValidateComponent(FacesContext pContext, UIComponent pComponent, Object pValue){ if (wEditingMode!=EditingMode.NONE){ if (wDAO!=null && pValue!=null){ String xSourceId = pContext.getExternalContext().getRequestParameterMap().get(DBSFaces.PARTIAL_SOURCE_PARAM); if (xSourceId !=null && !xSourceId.endsWith(":cancel")){ //TODO verificar se existe uma forma melhor de identificar se foi um cancelamento if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression(xInput); if (xColumn!=null){ String xValue = pValue.toString(); if (pValue instanceof Number){ xValue = DBSNumber.getOnlyNumber(xValue); } if (xValue.length() > xColumn.getSize()){ wMessageOverSize.setMessageTextParameters(xInput.getLabel(), xColumn.getSize()); addMessage(wMessageOverSize); wValidateComponentHasError = true; } } } } } } } public EditingMode getEditingMode() { return wEditingMode; } private synchronized void setEditingMode(EditingMode pEditingMode) { if (wEditingMode != pEditingMode){ //Qualquer troca no editingMode, desativa o editingstage setEditingStage(EditingStage.NONE); if (pEditingMode.equals(EditingMode.NONE)){ pvFireEventAfterEdit(wEditingMode); setValueChanged(false); } wEditingMode = pEditingMode; } } public EditingStage getEditingStage() { return wEditingStage; } private void setEditingStage(EditingStage pEditingStage) { if (wEditingStage != pEditingStage){ //Salva novo estado wEditingStage = pEditingStage; } } public void setDialogCaption(String pDialogCaption) {wDialogCaption = pDialogCaption;} public String getDialogCaption() {return wDialogCaption;} public Boolean getDialogOpened() { return wDialogOpened; } private synchronized void setDialogOpened(Boolean pDialogOpened) { if (wFormStyle == FormStyle.DIALOG){ if (wDialogOpened != pDialogOpened){ wDialogOpened = pDialogOpened; } } } public Boolean getDialogCloseAfterInsert() { return wDialogCloseAfterInsert; } public void setDialogCloseAfterInsert(Boolean pDialogCloseAfterInsert) { wDialogCloseAfterInsert = pDialogCloseAfterInsert; } public FormStyle getFormStyle() {return wFormStyle;} public void setFormStyle(FormStyle pFormStyle) {wFormStyle = pFormStyle;} @Override public String getMessageConfirmationEdit() {return wMessageConfirmationEdit;} @Override public void setMessageConfirmationEdit(String pMessageConfirmationEdit) {wMessageConfirmationEdit = pMessageConfirmationEdit;} @Override public String getMessageConfirmationInsert() {return wMessageConfirmationInsert;} @Override public void setMessageConfirmationInsert(String pDialogConfirmationInsertMessage) {wMessageConfirmationInsert = pDialogConfirmationInsertMessage;} @Override public String getMessageConfirmationDelete() {return wMessageConfirmationDelete;} @Override public void setMessageConfirmationDelete(String pMessageConfirmationDelete) {wMessageConfirmationDelete = pMessageConfirmationDelete;} @Override public String getMessageConfirmationApprove() {return wMessageConfirmationApprove;} @Override public void setMessageConfirmationApprove(String pMessageConfirmationApprove) {wMessageConfirmationApprove = pMessageConfirmationApprove;} @Override public String getMessageConfirmationReprove() {return wMessageConfirmationReprove;} @Override public void setMessageConfirmationReprove(String pMessageConfirmationReprove) {wMessageConfirmationReprove = pMessageConfirmationReprove;} @Override public String getMessageIgnoreEdit() {return wMessageIgnoreEdit;} @Override public void setMessageIgnoreEdit(String pMessageIgnoreEdit) {wMessageIgnoreEdit = pMessageIgnoreEdit;} @Override public String getMessageIgnoreInsert() {return wMessageIgnoreInsert;} @Override public void setMessageIgnoreInsert(String pMessageIgnoreInsert) {wMessageIgnoreInsert = pMessageIgnoreInsert;} @Override public String getMessageIgnoreDelete() {return wMessageIgnoreDelete;} @Override public void setMessageIgnoreDelete(String pMessageIgnoreDelete) {wMessageIgnoreDelete = pMessageIgnoreDelete;} @Override public Boolean getMessageConfirmationExists(){ if (getIsCommitting()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageConfirmationEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageConfirmationInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageConfirmationDelete())){ return false; } //TODO: ADICIONADO APROVACAO E REPROVACAO }else if (getIsApproving()){ if (DBSObject.isEmpty(getMessageConfirmationApprove())){ return false; } }else if (getIsReproving()){ if (DBSObject.isEmpty(getMessageConfirmationReprove())){ return false; } }else{ return false; } return true; } return false; } @Override public Boolean getMessageIgnoreExists(){ if (getIsIgnoring()){ if (getIsUpdating()){ if (DBSObject.isEmpty(getMessageIgnoreEdit())){ return false; } }else if (getIsInserting()){ if (DBSObject.isEmpty(getMessageIgnoreInsert())){ return false; } }else if (getIsDeleting()){ if (DBSObject.isEmpty(getMessageIgnoreDelete())){ return false; } }else{ return false; } return true; } return false; } public DBSResultDataModel getList() throws DBSIOException{ if (wDAO==null){ pvSearchList(); if (wDAO==null || wDAO.getResultDataModel() == null){ return new DBSResultDataModel(); } clearMessages(); } return wDAO.getResultDataModel(); } /** * Retorna a quantidade de registros da pesquisa principal. * @return * @throws DBSIOException */ public Integer getRowCount() throws DBSIOException{ if (getList() != null){ return getList().getRowCount(); }else{ return 0; } } public Boolean getAllowDelete() throws DBSIOException { return wAllowDelete && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowDelete(Boolean pAllowDelete) {wAllowDelete = pAllowDelete;} public Boolean getAllowUpdate() throws DBSIOException { return wAllowUpdate && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowUpdate(Boolean pAllowUpdate) {wAllowUpdate = pAllowUpdate;} public Boolean getAllowInsert() { return wAllowInsert && pvApprovalUserAllowRegister(); } public void setAllowInsert(Boolean pAllowInsert) { wAllowInsert = pAllowInsert; setAllowCopy(pAllowInsert); } public Boolean getAllowRefresh() {return wAllowRefresh;} public void setAllowRefresh(Boolean pAllowRefresh) {wAllowRefresh = pAllowRefresh;} public Boolean getMultipleSelection() {return wMultipleSelection;} public void setMultipleSelection(Boolean pMultipleSelection) {wMultipleSelection = pMultipleSelection;} public Boolean getAllowApproval() {return wAllowApproval;} public void setAllowApproval(Boolean pAllowApproval) {wAllowApproval = pAllowApproval;} public Boolean getAllowApprove(){return wAllowApprove;} public void setAllowApprove(Boolean pAllowApprove){wAllowApprove = pAllowApprove;} public Boolean getAllowReprove(){return wAllowReprove;} public void setAllowReprove(Boolean pAllowReprove){wAllowReprove = pAllowReprove;} public Boolean getAllowCopy(){return wAllowCopy;} public void setAllowCopy(Boolean pAllowCopy){wAllowCopy = pAllowCopy;} public Boolean getAllowCopyOnUpdate(){return wAllowCopyOnUpdate;} public void setAllowCopyOnUpdate(Boolean pAllowCopyOnUpdate){wAllowCopyOnUpdate = pAllowCopyOnUpdate;} public APPROVAL_STAGE getApprovalStage() throws DBSIOException { return pvGetApprovalStage(true); } public APPROVAL_STAGE getApprovalStageListValue() throws DBSIOException { return pvGetApprovalStage(false); } public void setApprovalStage(APPROVAL_STAGE pApprovalStage) { setValue(getColumnNameApprovalStage(), pApprovalStage.getCode()); } public APPROVAL_STAGE getApprovalUserNextStage() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserNextStageListValue() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserMaxStage(){ return DBSApproval.getMaxStage(getApprovalUserStages()); } public Integer getApprovalUserStages() {return wApprovalUserStages;} public void setApprovalUserStages(Integer pApprovalUserStages) {wApprovalUserStages = pApprovalUserStages;} public Boolean getIsApprovalStageRegistered() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public Boolean getIsApprovalStageVerified() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.VERIFIED; } public Boolean getIsApprovalStageConferred() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.CONFERRED; } public Boolean getIsApprovalStageApproved() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.APPROVED; } public String getColumnNameApprovalStage() {return wColumnNameApprovalStage;} public void setColumnNameApprovalStage(String pColumnNameApprovalStage) {wColumnNameApprovalStage = pColumnNameApprovalStage;} public String getColumnNameApprovalUserIdRegistered() {return wColumnNameApprovalUserIdRegistered;} public void setColumnNameApprovalUserIdRegistered(String pColumnNameApprovalUserIdRegistered) {wColumnNameApprovalUserIdRegistered = pColumnNameApprovalUserIdRegistered;} public String getColumnNameApprovalUserIdConferred() {return wColumnNameApprovalUserIdConferred;} public void setColumnNameApprovalUserIdConferred(String pColumnNameApprovalUserIdConferred) {wColumnNameApprovalUserIdConferred = pColumnNameApprovalUserIdConferred;} public String getColumnNameApprovalUserIdVerified() {return wColumnNameApprovalUserIdVerified;} public void setColumnNameApprovalUserIdVerified(String pColumnNameApprovalUserIdVerified) {wColumnNameApprovalUserIdVerified = pColumnNameApprovalUserIdVerified;} public String getColumnNameApprovalUserIdApproved() {return wColumnNameApprovalUserIdApproved;} public void setColumnNameApprovalUserIdApproved(String pColumnNameApprovalUserIdApproved) {wColumnNameApprovalUserIdApproved = pColumnNameApprovalUserIdApproved;} public String getColumnNameApprovalDateApproved() {return wColumnNameApprovalDateApproved;} public void setColumnNameApprovalDateApproved(String pColumnNameApprovalDateApproved) {wColumnNameApprovalDateApproved = pColumnNameApprovalDateApproved;} public String getColumnNameDateOnInsert() {return wColumnNameDateOnInsert;} public void setColumnNameDateOnInsert(String pColumnNameDateOnInsert) {wColumnNameDateOnInsert = pColumnNameDateOnInsert;} public String getColumnNameDateOnUpdate() {return wColumnNameDateOnUpdate;} public void setColumnNameDateOnUpdate(String pColumnNameDateOnUpdate) {wColumnNameDateOnUpdate = pColumnNameDateOnUpdate;} public String getColumnNameUserIdOnInsert() {return wColumnNameUserIdOnInsert;} public void setColumnNameUserIdOnInsert(String pColumnNameUserIdOnInsert) {wColumnNameUserIdOnInsert = pColumnNameUserIdOnInsert;} public String getColumnNameUserIdOnUpdate() {return wColumnNameUserIdOnUpdate;} public void setColumnNameUserIdOnUpdate(String pColumnNameUserIdOnUpdate) {wColumnNameUserIdOnUpdate = pColumnNameUserIdOnUpdate;} public void setSortColumn(String pSortColumn){wSortColumn = pSortColumn;} public String getSortColumn(){return wSortColumn;} public void setSortDirection(String pSortDirection){wSortDirection = pSortDirection;} public String getSortDirection(){return wSortDirection;} public Boolean getRevalidateBeforeCommit() {return wRevalidateBeforeCommit;} public void setRevalidateBeforeCommit(Boolean pRevalidateBeforeCommit) {wRevalidateBeforeCommit = pRevalidateBeforeCommit;} public Integer getUserId() {return wUserId;} public void setUserId(Integer pUserId) {wUserId = pUserId;} public void setParentCrudBean(DBSCrudBean pCrudBean) { wParentCrudBean = pCrudBean; if (!pCrudBean.getChildrenCrudBean().contains(this)){ pCrudBean.getChildrenCrudBean().add(this); } } public DBSCrudBean getParentCrudBean() { return wParentCrudBean; } public List<DBSCrudBean> getChildrenCrudBean() { return wChildrenCrudBean; } public void setValueChanged(Boolean pChanged){ wValueChanged = pChanged; } public boolean getIsValueChanged(){ return wValueChanged; } @Override public Boolean getIsCommitting(){ return (wEditingStage == EditingStage.COMMITTING); } @Override public Boolean getIsUpdating(){ return (wEditingMode == EditingMode.UPDATING); } public Boolean getIsEditing(){ return (wEditingMode != EditingMode.NONE); } @Override public Boolean getIsDeleting(){ return (wEditingMode == EditingMode.DELETING); } public Boolean getIsApproving(){ return (wEditingMode == EditingMode.APPROVING); } public Boolean getIsReproving(){ return (wEditingMode == EditingMode.REPROVING); } // public Boolean getIsApprovalStageApproved(Integer pApprovalStage){ // return DBSApproval.isApproved(pApprovalStage); // public Boolean getIsApprovalStageConferred(Integer pApprovalStage){ // return DBSApproval.isConferred(pApprovalStage); // public Boolean getIsApprovalStageVerified(Integer pApprovalStage){ // return DBSApproval.isVerified(pApprovalStage); // public Boolean getIsApprovalStageRegistered(Integer pApprovalStage){ // return DBSApproval.isRegistered(pApprovalStage); public Boolean getIsApprovingOrReproving(){ return (wEditingMode == EditingMode.APPROVING || wEditingMode == EditingMode.REPROVING); } @Override public Boolean getIsIgnoring(){ return (wEditingStage == EditingStage.IGNORING); } public Boolean getIsFirst(){ if (wDAO != null){ return wDAO.getIsFist(); }else{ return true; } } public Boolean getIsLast(){ if (wDAO != null){ return wDAO.getIsLast(); }else{ return true; } } public Boolean getIsViewing(){ return (wEditingMode == EditingMode.NONE); } @Override public Boolean getIsInserting(){ return (wEditingMode == EditingMode.INSERTING); } public Boolean getIsEditingDisabled(){ if (wAllowApproval || wAllowDelete || wAllowInsert || wAllowUpdate){ return false; } return true; } public void setDisableEditing(){ setAllowApproval(false); setAllowDelete(false); setAllowInsert(false); setAllowUpdate(false); } public Boolean getIsReadOnly(){ if (getIsViewing() || wEditingMode == EditingMode.DELETING){ return true; }else{ return false; } } public Boolean getIsClosed(){ return (!wDialogOpened); } /** * Se tem algumm registro copiado * @return */ public Boolean getIsCopied(){ if (wCopiedRowIndex != -1){ return true; }else{ return false; } } // Methods /** * Retorna lista dos itens selecionados * @return */ public List<Integer> getSelectedRowsIndexes(){ return wSelectedRowsIndexes; } public Boolean getSelected() throws DBSIOException { if (wSelectedRowsIndexes.contains(getList().getRowIndex())){ return true; } return false; } public void setSelected(Boolean pSelectOne) throws DBSIOException { // wDAO.synchronize(); pvSetSelected(pSelectOne); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSetSelected(!pSelectOne); } } public boolean getHasSelected(){ if (wSelectedRowsIndexes != null){ if (wSelectedRowsIndexes.size()>0){ return true; } } return false; } /** * Selectiona todas as linhas que exibidas */ public synchronized String selectAll() throws DBSIOException{ if (!wDialogOpened){ pvSelectAll(); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSelectAll(); } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String confirmEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ if (wValidateComponentHasError){ wValidateComponentHasError = false; }else{ if ((getIsValueChanged() && getIsDeleting() == false) || getIsDeleting()){ if (pvFireEventBeforeValidate() && pvFireEventValidate()){ setEditingStage(EditingStage.COMMITTING); if (!getMessageConfirmationExists()){ return endEditing(true); } }else{ if(getIsDeleting() || getIsApprovingOrReproving()){ setEditingMode(EditingMode.NONE); } } }else{ addMessage(wMessageNoChange); } } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String ignoreEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ //Disparado eventos antes de ignorar setEditingStage(EditingStage.IGNORING); if (!getIsValueChanged()){ return endEditing(true); } if (!getMessageIgnoreExists()){ return endEditing(true); } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } @Override public synchronized String endEditing(Boolean pConfirm) throws DBSIOException{ try{ if (pConfirm){ if (wEditingStage!=EditingStage.NONE){ if (wEditingStage==EditingStage.COMMITTING){ //Disparando eventos if (pvFireEventValidate() && pvFireEventBeforeCommit()){ pvFireEventAfterCommit(); pvSearchList(); pvEndEditing(true); }else{ pvEndEditing(false); } }else if (wEditingStage==EditingStage.IGNORING){ //Disparando eventos if (pvFireEventBeforeIgnore()){ pvFireEventAfterIgnore(); pvEndEditing(true); }else{ pvEndEditing(false); } } }else{ //exibe mensagem de erro de procedimento } }else{ setEditingStage(EditingStage.NONE); switch(wEditingMode){ case UPDATING: break; case INSERTING: break; case DELETING: setEditingMode(EditingMode.NONE); view(); break; case APPROVING: setEditingMode(EditingMode.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); close(false); break; default: //Exibe mensagem de erro de procedimento } } }catch(Exception e){ wLogger.error("Crud:" + getDialogCaption() + ":endEditing", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } return DBSFaces.getCurrentView(); } public String beginEditingView() throws DBSIOException{ if (getFormStyle() != FormStyle.VIEW){ return DBSFaces.getCurrentView(); } if (getEditingMode() != EditingMode.NONE){ return DBSFaces.getCurrentView(); } try{ openConnection(); //Le o registro beforeRefresh(null); if (wConnection != null){ moveFirst(); //Verifica se existe registro corrente if (wDAO != null && wDAO.getCurrentRowIndex() > -1){ return update(); }else{ return insert(); } } return insert(); }finally{ if (wConnection != null){ closeConnection(); } } } // Methods public synchronized String searchList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvSearchList(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return DBSFaces.getCurrentView(); } public synchronized String refreshList() throws DBSIOException{ boolean xOpenConnection = false; if (wParentCrudBean!=null && !DBSIO.isConnectionOpened(wParentCrudBean.wConnection)){ xOpenConnection = true; wParentCrudBean.openConnection(); } pvFireEventInitialize(); if (xOpenConnection){ wParentCrudBean.closeConnection(); } return searchList(); } public synchronized String copy() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ wCopiedRowIndex = wDAO.getCurrentRowIndex(); pvFireEventAfterCopy(); } return DBSFaces.getCurrentView(); } /** * Seta os valores atuais com os valores do registro copiado * @throws DBSIOException */ public synchronized String paste() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ if (pvFireEventBeforePaste()){ //Seta o registro atual como sendo o registro copiado wDAO.paste(wCopiedRowIndex); setValueChanged(true); } } return DBSFaces.getCurrentView(); } /** * Exibe todos os itens selecionados */ public synchronized String viewSelection() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} //Limpa todas as mensagens que estiverem na fila clearMessages(); if (wDAO.getCurrentRowIndex() != -1){ if (!wDialogOpened){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Exibe o item selecionado */ public synchronized String view() throws DBSIOException{ if (wFormStyle == FormStyle.TABLE){return DBSFaces.getCurrentView();} if (wFormStyle == FormStyle.DIALOG){ //Limpa todas as mensagens que estiverem na fila clearMessages(); } if (wConnection != null && wDAO.getCurrentRowIndex()!=-1){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } /** * Informa com cadastro foi fechado */ public synchronized String close() throws DBSIOException{ return close(true); } /** * Informa que cadastro foi fechado */ public synchronized String close(Boolean pClearMessage) throws DBSIOException{ if (wDialogOpened){ //Dispara evento if (pvFireEventBeforeClose()){ setDialogOpened(false); if (pClearMessage) { clearMessages(); } } //getLastInstance("a"); }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String insertSelected() throws DBSIOException{ setDialogCloseAfterInsert(true); view(); copy(); insert(); paste(); wCopiedRowIndex = -1; return DBSFaces.getCurrentView(); } public synchronized void sort() throws DBSIOException{} public synchronized String insert() throws DBSIOException{ if (wAllowInsert || wDialogCloseAfterInsert){ if (!wDialogCloseAfterInsert){ if (wFormStyle == FormStyle.DIALOG){ clearMessages(); } } if (wFormStyle == FormStyle.TABLE && wEditingMode==EditingMode.UPDATING){ pvInsertEmptyRow(); }else{ if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeInsert() && pvFireEventBeforeEdit(EditingMode.INSERTING)){ //Desmarca registros selecionados wSelectedRowsIndexes.clear(); setEditingMode(EditingMode.INSERTING); setDialogOpened(true); }else{ setValueChanged(false); } // if (pvFireEventBeforeEdit(EditingMode.INSERTING)){ // //Desmarca registros selecionados // wSelectedRowsIndexes.clear(); // setEditingMode(EditingMode.INSERTING); // pvMoveBeforeFistRow(); // //Dispara evento BeforeInsert // if (pvFireEventBeforeInsert()){ // setDialogOpened(true); // }else{ // setValueChanged(false); // //exibe mensagem de erro de procedimento } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":insert", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } } return DBSFaces.getCurrentView(); } public synchronized String update() throws DBSIOException{ if (wAllowUpdate){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.UPDATING)){ setEditingMode(EditingMode.UPDATING); pvInsertEmptyRow(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":update", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String delete() throws DBSIOException{ if (wAllowDelete){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.DELETING)){ setEditingMode(EditingMode.DELETING); confirmEditing(); //setEditingStage(EditingStage.COMMITTING); }else{ setValueChanged(false); //setEditingStage(EditingStage.COMMITTING); } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":delete", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String approve() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.APPROVING)){ setEditingMode(EditingMode.APPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":approve", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String reprove() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.REPROVING)){ setEditingMode(EditingMode.REPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":reprove", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Move para o primeiro registro. * @return * @throws DBSIOException */ public synchronized String moveFirst() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveFirstRow(); view(); } return DBSFaces.getCurrentView(); } /** * Move para o registro anterior * @return * @throws DBSIOException */ public synchronized String movePrevious() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.movePreviousRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveNext() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveNextRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveLast() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveLastRow(); view(); } return DBSFaces.getCurrentView(); } @Override protected void warningMessageValidated(String pMessageKey, Boolean pIsValidated) throws DBSIOException{ //Se mensagem de warning foi validade.. if (pIsValidated){ confirmEditing(); }else{ if (getEditingMode().equals(EditingMode.DELETING)){ ignoreEditing(); } } } @Override protected boolean openConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.openConnection(); if (wDAO !=null){ wDAO.setConnection(wConnection); } //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); return true; } } return false; } @Override protected void closeConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.closeConnection(); //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); } } } // Abstracted protected abstract void initialize(DBSCrudBeanEvent pEvent) throws DBSIOException; protected void finalize(DBSCrudBeanEvent pEvent){}; protected void beforeClose(DBSCrudBeanEvent pEvent) throws DBSIOException {} ; protected void beforeRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void afterEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void beforeInsert(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeCommit(DBSCrudBeanEvent pEvent) throws DBSIOException { //Copia dos valores pois podem ter sido alterados durante o beforecommit if (wConnection == null){return;} if (getIsApprovingOrReproving()){ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ pEvent.setCommittedRowCount(wDAO.executeUpdate()); }else{ return; } //Insert/Update/Delete }else{ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ //Insert if(getIsInserting()){ if (wDAO.isAutoIncrementPK()){ wDAO.setValue(wDAO.getPK(), null); } pEvent.setCommittedRowCount(wDAO.executeInsert()); //Update }else if (getIsUpdating()){ if (wFormStyle == FormStyle.TABLE && wDAO.getIsNewRow()){ pEvent.setCommittedRowCount(wDAO.executeInsert()); }else{ pEvent.setCommittedRowCount(wDAO.executeUpdate()); } //Delete }else if(getIsDeleting()){ pEvent.setCommittedRowCount(wDAO.executeDelete()); } } } } protected void afterCommit(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void beforeIgnore(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterIgnore(DBSCrudBeanEvent pEvent){} protected void beforeSelect(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterSelect(DBSCrudBeanEvent pEvent){} protected void beforeValidate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void validate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void afterCopy(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforePaste(DBSCrudBeanEvent pEvent) throws DBSIOException{}; private void pvConversationBegin(){ // if (!FacesContext.getCurrentInstance().isPostback() && wConversation.isTransient()){ if (wConversation.isTransient()){ wConversation.begin(); wConversation.setTimeout(wConversationTimeout); } } /** * Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh.<br/> * @throws DBSIOException */ private void pvSearchList() throws DBSIOException{ if (getEditingMode() == EditingMode.UPDATING){ ignoreEditing(); } //Dispara evento para atualizar os dados if (pvFireEventBeforeRefresh()){ //Apaga itens selecionados, se houver. wSelectedRowsIndexes.clear(); pvFireEventAfterRefresh(); } } private void pvEndEditing(Boolean pOk) throws DBSIOException{ switch(wEditingMode){ case UPDATING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); pvRestoreValuesOriginal(); pvSearchList(); view(); }else{ if (pOk){ setEditingMode(EditingMode.NONE); view(); }else{ setEditingStage(EditingStage.NONE); } } break; case INSERTING: if (pOk){ if (wEditingStage==EditingStage.IGNORING || wDialogCloseAfterInsert){ setEditingMode(EditingMode.NONE); close(); }else{ setEditingMode(EditingMode.NONE); if (getFormStyle() == FormStyle.VIEW){ view(); }else{ insert(); } } }else{ setEditingStage(EditingStage.NONE); } break; case DELETING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); }else{ wCopiedRowIndex = -1; setEditingMode(EditingMode.NONE); if (pOk){ setDialogOpened(false); } } break; case APPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; default: setEditingMode(EditingMode.NONE); //Exibe mensagem de erro de procedimento } } private void pvRestoreValuesOriginal(){ wDAO.restoreValuesOriginal(); } /** * Move para o registro anterior ao primeiro registro. * @throws DBSIOException */ private void pvMoveBeforeFistRow() throws DBSIOException{ wDAO.moveBeforeFirstRow(); } private void pvInsertEmptyRow() throws DBSIOException{ if (wFormStyle != FormStyle.TABLE || wEditingMode != EditingMode.UPDATING || !wAllowInsert){ return; } wDAO.insertEmptyRow(); pvFireEventBeforeInsert(); } private DBSColumn pvGetDAOColumnFromInputValueExpression(DBSUIInput pInput){ String xColumnName = DBSFaces.getAttibuteNameFromInputValueExpression(pInput).toLowerCase(); if (xColumnName!=null && !xColumnName.equals("")){ //Retira do os prefixos controlados pelo sistema para encontrar o nome da coluna if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName().length()); }else if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName().length()); } if (wDAO.containsColumn(xColumnName)){ return wDAO.getColumn(xColumnName); } } return null; } private void pvBroadcastConnection(DBSCrudBean pBean){ for (DBSCrudBean xChildBean:pBean.getChildrenCrudBean()){ Connection xCn = xChildBean.getConnection(); if (!xCn.equals(pBean.getConnection())){ DBSIO.closeConnection(xCn); xChildBean.setConnection(pBean.getConnection()); } //Procura pelos netos pvBroadcastConnection(xChildBean); } } /** * Salva indice do linha selacionada * @param pSelectOne * @throws DBSIOException */ private void pvSetSelected(Boolean pSelectOne) throws DBSIOException{ Integer xRowIndex = getList().getRowIndex(); if (pSelectOne){ if (wFormStyle == FormStyle.TABLE){ setValueChanged(true); } if (!wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.add(xRowIndex); } }else{ if (wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.remove(xRowIndex); } } } private void pvSelectAll() throws DBSIOException{ for (Integer xX = 0; xX < getList().getRowCount(); xX++){ if (wSelectedRowsIndexes.contains(xX)){ wSelectedRowsIndexes.remove(xX); }else{ wSelectedRowsIndexes.add(xX); } } } /** * Seta o valor da coluna no DAO * @param pColumnName * @param pColumnValue */ private void pvSetValueDAO(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ Object xOldValue = pvGetValue(pColumnName); if (pColumnValue != null){ xOldValue = DBSObject.toClassValue(xOldValue, pColumnValue.getClass()); } if(!DBSObject.getNotNull(xOldValue,"").toString().equals(DBSObject.getNotNull(pColumnValue,"").toString())){ if (getEditingMode() == EditingMode.INSERTING && getDialogOpened()){ wLogger.info("ALTERADO:" + pColumnName + "[" + DBSObject.getNotNull(xOldValue,"") + "] para [" + DBSObject.getNotNull(pColumnValue,"") + "]"); } //marca como valor alterado setValueChanged(true); wDAO.setValue(pColumnName, pColumnValue); } } } /** * Retorna valor da coluna a partir do DAO * @param pColumnName * @return */ @SuppressWarnings("unchecked") private <T> T pvGetValue(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValue(pColumnName); }else{ return null; } } private APPROVAL_STAGE pvGetApprovalStage(boolean pFromValue){ if (!getAllowApproval()){ return APPROVAL_STAGE.REGISTERED; } APPROVAL_STAGE xStage; if (pFromValue){ xStage = APPROVAL_STAGE.get(getValue(getColumnNameApprovalStage())); }else{ xStage = APPROVAL_STAGE.get(getListValue(getColumnNameApprovalStage())); } if (xStage==null){ xStage = APPROVAL_STAGE.REGISTERED; } return xStage; } private boolean pvApprovalUserAllowRegister(){ if (getAllowApproval() && !DBSApproval.isRegistered(getApprovalUserStages())){ return false; } return true; } private Integer pvGetApprovalNextUserStages() throws DBSIOException{ return DBSApproval.getNextUserStages(getApprovalStage(), getApprovalUserStages()); } private APPROVAL_STAGE pvGetApprovalNextUserStage() throws DBSIOException{ return DBSApproval.getMaxStage(pvGetApprovalNextUserStages()); } private void pvBeforeCommitSetAutomaticColumnsValues(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; //Delete if(wConnection == null || getIsDeleting()){ return; } //Configura os valores das assinaturas se assinatura estive habilitada. if (getAllowApproval()){ pvBeforeCommitSetAutomaticColumnsValuesApproval(pEvent); } //Insert if(getIsInserting()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnInsert()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnInsert()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } //Update }else if (getIsUpdating()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnUpdate()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnUpdate()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } } } private void pvBeforeCommitSetAutomaticColumnsValuesApproval(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; APPROVAL_STAGE xApprovalNextStage = null; Integer xUserId = null; Timestamp xApprovalDate = null; Integer xApprovalNextUserStages = null; xUserId = getUserId(); xApprovalDate = DBSDate.getNowTimestamp(); if (getIsApproving()){ xApprovalNextUserStages = pvGetApprovalNextUserStages(); xApprovalNextStage = pvGetApprovalNextUserStage(); }else if (getIsReproving()){ xApprovalNextUserStages = DBSApproval.getApprovalStage(false, true, true, true); xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xUserId = null; xApprovalDate = null; }else if(getIsInserting() || getIsUpdating()){ xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xApprovalNextUserStages = APPROVAL_STAGE.REGISTERED.getCode(); } if (xApprovalNextStage==APPROVAL_STAGE.REGISTERED){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){xColumn.setValue(getUserId());} }else{ if (DBSApproval.isConferred(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdConferred()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isVerified(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdVerified()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isApproved(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){ if (DBSNumber.toInteger(xColumn.getValue()).equals(xUserId)){ addMessage(wMessaggeApprovalSameUser); pEvent.setOk(false); return; } } xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdApproved()); if (xColumn!=null){xColumn.setValue(xUserId);} xColumn = wDAO.getCommandColumn(getColumnNameApprovalDateApproved()); if (xColumn!=null){xColumn.setValue(xApprovalDate);} } } setApprovalStage(xApprovalNextStage); } private void pvCurrentRowSave(){ wSavedCurrentColumns = null; if (wDAO != null){ wSavedCurrentColumns = wDAO.getCommandColumns(); //utiliza as colunas da query if (wDAO.getCommandColumns() == null || wDAO.getCommandColumns().size() == 0){ wSavedCurrentColumns = wDAO.getColumns(); } } } private void pvCurrentRowRestore() throws DBSIOException{ boolean xOk; Object xSavedValue = null; Object xCurrentValue = null; BigDecimal xSavedNumberValue = null; BigDecimal xCurrentNumberValue = null; boolean xEqual; if (wDAO != null){ wDAO.moveBeforeFirstRow(); if (wSavedCurrentColumns !=null && wSavedCurrentColumns.size() > 0 && wDAO.getResultDataModel() != null){ DBSResultDataModel xQueryRows = wDAO.getResultDataModel(); for (int xRowIndex = 0; xRowIndex <= xQueryRows.getRowCount()-1; xRowIndex++){ xQueryRows.setRowIndex(xRowIndex); xOk = true; //Loop por todas as colunas da linha da query for (String xQueryColumnName:xQueryRows.getRowData().keySet()){ Object xQueryColumnValue = xQueryRows.getRowData().get(xQueryColumnName); //Procura pelo coluna que possua o mesmo nome for (DBSColumn xColumnSaved: wSavedCurrentColumns){ if (xColumnSaved.getColumnName().equalsIgnoreCase(xQueryColumnName)){ xSavedValue = DBSObject.getNotNull(xColumnSaved.getValue(),""); xCurrentValue = DBSObject.getNotNull(xQueryColumnValue,""); xEqual = false; if (xCurrentValue == null && xSavedValue == null){ xEqual = true; }else if (xCurrentValue instanceof Number){ xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); if (xSavedValue instanceof Number){ xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); } if (xSavedNumberValue != null && xCurrentNumberValue != null){ if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ xEqual = true; } } }else{ xEqual = xSavedValue.equals(xCurrentValue); } if (!xEqual){ xOk = false; } break; } } if (!xOk){ break; } } if (xOk){ return; } } if (wDAO != null){ wDAO.moveFirstRow(); } } } } // private void pvCurrentRowRestore() throws DBSIOException{ // boolean xOk; // Integer xRowIndex; // Object xSavedValue = null; // Object xCurrentValue = null; // BigDecimal xSavedNumberValue = null; // BigDecimal xCurrentNumberValue = null; // boolean xEqual; // if (wDAO != null // && wSavedCurrentColumns !=null // && wSavedCurrentColumns.size() > 0 // && wDAO.getResultDataModel() != null){ // //Recupera todas as linhas // Iterator<SortedMap<String, Object>> xIR = wDAO.getResultDataModel().iterator(); // xRowIndex = -1; // while (xIR.hasNext()){ // xOk = true; // xRowIndex++; // //Recupera todas as colunas da linha // SortedMap<String, Object> xColumns = xIR.next(); // //Loop por todas as colunas da linha // for (Entry<String, Object> xC:xColumns.entrySet()){ // Iterator<DBSColumn> xIS = wSavedCurrentColumns.iterator(); // //Procura pelo coluna que possua o mesmo nome // while (xIS.hasNext()){ // DBSColumn xSC = xIS.next(); // if (xSC.getColumnName().equalsIgnoreCase(xC.getKey())){ // xSavedValue = DBSObject.getNotNull(xSC.getValue(),""); // xCurrentValue = DBSObject.getNotNull(xC.getValue(),""); // xEqual = false; // if (xCurrentValue == null // && xSavedValue == null){ // xEqual = true; // }else if (xCurrentValue instanceof Number){ // xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); // if (xSavedValue instanceof Number){ // xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); // if (xSavedNumberValue != null // && xCurrentNumberValue != null){ // if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ // xEqual = true; // }else{ // xEqual = xSavedValue.equals(xCurrentValue); // if (!xEqual){ // xOk = false; // break; // if (!xOk){ // break; // if (xOk){ // wDAO.setCurrentRowIndex(xRowIndex); // return; //// if (wParentCrudBean == null){ // if (wDAO != null){ // wDAO.moveFirstRow(); private void pvFireEventInitialize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.INITIALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private void pvFireEventFinalize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.FINALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventFinalize",e); } } private boolean pvFireEventBeforeClose(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_CLOSE, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeClose",e); } return xE.isOk(); } private boolean pvFireEventBeforeView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VIEW, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeView",e); } return xE.isOk(); } private void pvFireEventAfterView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_VIEW, getEditingMode()); setValueChanged(false); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterView",e); } } private boolean pvFireEventBeforeInsert() throws DBSIOException{ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_INSERT, getEditingMode()); if (wDAO != null){ openConnection(); pvMoveBeforeFistRow(); closeConnection(); } // pvBeforeInsertResetValues(wCrudForm); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeInsert",e); } setValueChanged(false); return xE.isOk(); } private boolean pvFireEventBeforeEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_EDIT, pEditingMode); setValueChanged(false); try{ pvBroadcastEvent(xE, false, true, false); return xE.isOk(); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeEdit",e); } return xE.isOk(); } private boolean pvFireEventAfterEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_EDIT, pEditingMode); try{ pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterEdir",e); } return xE.isOk(); } private boolean pvFireEventBeforeRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeRefresh",e); } return xE.isOk(); } private void pvFireEventAfterRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private boolean pvFireEventBeforeIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private boolean pvFireEventBeforeValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.notSelected")); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeValidate",e); } return xE.isOk(); } private boolean pvFireEventValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); if (!xE.isOk()){ if (getIsApprovingOrReproving()){ addMessage("erroassinatura", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvalAll")); break; }else{ addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.editAll")); break; } } } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.notSelected")); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventValidate",e); } return xE.isOk(); } private boolean pvFireEventBeforeCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_COMMIT, getEditingMode()); String xErrorMsg = null; //Chame o metodo(evento) local para quando esta classe for extendida try { //Zera a quantidade de registros afetados xE.setCommittedRowCount(0); if (wConnection != null){ wDAO.setConnection(wConnection); //Se for o crud principal if (wParentCrudBean == null){ DBSIO.beginTrans(wConnection); } } if (getIsApprovingOrReproving() || wFormStyle == FormStyle.TABLE){ if (getHasSelected()){ int xCount = 0; wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); if (wFormStyle == FormStyle.TABLE){ wDAO.setExecuteOnlyChangedValues(false); } pvBroadcastEvent(xE, false, false, false); xCount += xE.getCommittedRowCount(); if (!xE.isOk()){ break; } } //Ignora assinatura caso quantidade todal de registros afetados seja inferior a quantidade de itens selectionados if (xCount < wSelectedRowsIndexes.size()){ xE.setCommittedRowCount(0); xE.setOk(false); addMessage("erroassinatura", MESSAGE_TYPE.ERROR, DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.approvalAll")); }else{ xE.setCommittedRowCount(xCount); } } }else{ pvBroadcastEvent(xE, false, false, false); } if (!wMessages.hasMessages() && (!xE.isOk() || (wConnection != null && xE.getCommittedRowCount().equals(0)))){ xE.setOk(false); addMessage(wMessageNoRowComitted); } //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, xE.isOk()); } } } catch (Exception e) { xE.setOk(false); try { //Se for o crud principal if (wConnection != null){ if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, false); } } if (e instanceof DBSIOException){ DBSIOException xDBException = (DBSIOException) e; xErrorMsg = e.getMessage(); if (xDBException.isIntegrityConstraint()){ clearMessages(); // addMessage("integridate", MESSAGE_TYPE.ERROR, xDBException.getLocalizedMessage()); }else{ wLogger.error("EventBeforeCommit", e); } wMessageError.setMessageText(xDBException.getLocalizedMessage()); wMessageError.setMessageTooltip(xErrorMsg); addMessage(wMessageError); }else{ wMessageError.setMessageText(DBSFaces.getBundlePropertyValue("dbsfaces", "crudbean.msg.support")); wMessageError.setMessageTooltip(e.getLocalizedMessage()); addMessage(wMessageError); } } catch (DBSIOException e1) { xErrorMsg = e1.getMessage(); } wMessageNoRowComitted.setMessageTooltip(xErrorMsg); addMessage(wMessageNoRowComitted); } return xE.isOk(); } private void pvFireEventAfterCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COMMIT, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); if (wParentCrudBean!=null){ wParentCrudBean.setValueChanged(true); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCommit",e); } } private boolean pvFireEventBeforeSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private void pvFireEventAfterCopy(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COPY, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCopy",e); } } /** * Disparado antes do paste. * @return */ private boolean pvFireEventBeforePaste(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_PASTE, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforePaste",e); } return xE.isOk(); } private void pvBroadcastEvent(DBSCrudBeanEvent pEvent, boolean pInvokeChildren, boolean pOpenConnection, boolean pCloseConnection) throws Exception { try{ if (pOpenConnection){ openConnection(); } wBrodcastingEvent = true; pvFireEventLocal(pEvent); if (pInvokeChildren){ pvFireEventChildren(pEvent); } pvFireEventListeners(pEvent); }catch(DBSIOException e){ wMessageError.setMessageText(e.getLocalizedMessage()); wMessageError.setMessageTooltip(e.getOriginalException().getLocalizedMessage()); if (!DBSObject.isEmpty(e.getCause())){ wMessageError.setMessageTooltip(e.getCause().getMessage() + "<br/>" + e.getMessage()); } addMessage(wMessageError); pEvent.setOk(false); // wLogger.error(pEvent.getEvent().toString(), e); }catch(Exception e){ String xStr = pEvent.getEvent().toString() + ":" + DBSObject.getNotNull(this.getDialogCaption(),"") + ":"; if (e.getLocalizedMessage()!=null){ xStr = xStr + e.getLocalizedMessage(); }else{ xStr = xStr + e.getClass(); } wMessageError.setMessageTextParameters(xStr); addMessage(wMessageError); pEvent.setOk(false); wLogger.error(pEvent.getEvent().toString(), e); throw e; }finally{ wBrodcastingEvent = false; if (pCloseConnection || !pEvent.isOk()){ closeConnection(); } } } private void pvFireEventLocal(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ switch (pEvent.getEvent()) { case INITIALIZE: initialize(pEvent); break; case FINALIZE: finalize(pEvent); break; case BEFORE_CLOSE: beforeClose(pEvent); break; case BEFORE_VIEW: beforeView(pEvent); break; case AFTER_VIEW: afterView(pEvent); break; case BEFORE_INSERT: beforeInsert(pEvent); break; case BEFORE_REFRESH: pvCurrentRowSave(); beforeRefresh(pEvent); pvCurrentRowRestore(); break; case AFTER_REFRESH: afterRefresh(pEvent); break; case BEFORE_COMMIT: beforeCommit(pEvent); break; case AFTER_COMMIT: afterCommit(pEvent); break; case BEFORE_IGNORE: beforeIgnore(pEvent); break; case AFTER_IGNORE: afterIgnore(pEvent); break; case BEFORE_EDIT: beforeEdit(pEvent); break; case AFTER_EDIT: afterEdit(pEvent); break; case BEFORE_SELECT: beforeSelect(pEvent); break; case AFTER_SELECT: afterSelect(pEvent); break; case BEFORE_VALIDATE: beforeValidate(pEvent); break; case VALIDATE: validate(pEvent); break; case AFTER_COPY: afterCopy(pEvent); break; case BEFORE_PASTE: beforePaste(pEvent); break; default: break; } } } /** * Dispara o evento nos beans vinculados a este bean * @param pEvent * @throws DBSIOException */ private void pvFireEventChildren(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ //Busca por beans vinculados e este bean for (DBSCrudBean xBean:wChildrenCrudBean){ if (pEvent.getEvent() == CRUD_EVENT.BEFORE_VIEW || pEvent.getEvent() == CRUD_EVENT.BEFORE_INSERT){ xBean.searchList(); } switch (pEvent.getEvent()) { case INITIALIZE: xBean.initialize(pEvent); break; case FINALIZE: xBean.finalize(pEvent); break; case BEFORE_CLOSE: xBean.beforeClose(pEvent); break; case BEFORE_VIEW: xBean.beforeView(pEvent); break; case AFTER_VIEW: xBean.afterView(pEvent); break; case BEFORE_INSERT: xBean.beforeInsert(pEvent); break; case BEFORE_REFRESH: xBean.beforeRefresh(pEvent); break; case AFTER_REFRESH: xBean.afterRefresh(pEvent); break; case BEFORE_COMMIT: xBean.beforeCommit(pEvent); break; case AFTER_COMMIT: xBean.afterCommit(pEvent); break; case BEFORE_IGNORE: xBean.beforeIgnore(pEvent); break; case AFTER_IGNORE: xBean.afterIgnore(pEvent); break; case BEFORE_EDIT: xBean.beforeEdit(pEvent); break; case AFTER_EDIT: xBean.afterEdit(pEvent); break; case BEFORE_SELECT: xBean.beforeSelect(pEvent); break; case AFTER_SELECT: xBean.afterSelect(pEvent); break; case BEFORE_VALIDATE: xBean.beforeValidate(pEvent); break; case VALIDATE: xBean.validate(pEvent); break; case AFTER_COPY: xBean.afterCopy(pEvent); break; case BEFORE_PASTE: xBean.beforePaste(pEvent); break; default: break; } if (!pEvent.isOk()){ break; } } } } private void pvFireEventListeners(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ for (int xX=0; xX<wEventListeners.size(); xX++){ switch (pEvent.getEvent()) { case INITIALIZE: wEventListeners.get(xX).initialize(pEvent); break; case FINALIZE: wEventListeners.get(xX).finalize(pEvent); break; case BEFORE_CLOSE: wEventListeners.get(xX).beforeClose(pEvent); break; case BEFORE_VIEW: wEventListeners.get(xX).beforeView(pEvent); break; case AFTER_VIEW: wEventListeners.get(xX).afterView(pEvent); break; case BEFORE_REFRESH: wEventListeners.get(xX).beforeRefresh(pEvent); break; case BEFORE_INSERT: wEventListeners.get(xX).beforeInsert(pEvent); break; case AFTER_REFRESH: wEventListeners.get(xX).afterRefresh(pEvent); break; case BEFORE_COMMIT: wEventListeners.get(xX).beforeCommit(pEvent); break; case AFTER_COMMIT: wEventListeners.get(xX).afterCommit(pEvent); break; case BEFORE_IGNORE: wEventListeners.get(xX).beforeIgnore(pEvent); break; case AFTER_IGNORE: wEventListeners.get(xX).afterIgnore(pEvent); break; case BEFORE_EDIT: wEventListeners.get(xX).beforeEdit(pEvent); break; case AFTER_EDIT: wEventListeners.get(xX).afterEdit(pEvent); break; case BEFORE_SELECT: wEventListeners.get(xX).beforeSelect(pEvent); break; case AFTER_SELECT: wEventListeners.get(xX).afterSelect(pEvent); break; case BEFORE_VALIDATE: wEventListeners.get(xX).beforeValidate(pEvent); break; case VALIDATE: wEventListeners.get(xX).validate(pEvent); break; case AFTER_COPY: wEventListeners.get(xX).afterCopy(pEvent); break; case BEFORE_PASTE: wEventListeners.get(xX).beforePaste(pEvent); break; default: break; } //Sa do loop se encontrar erro if (!pEvent.isOk()){ break; } } } } }
package br.com.dbsoft.ui.bean.crud; import java.math.BigDecimal; import java.sql.Connection; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.enterprise.context.Conversation; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.dbsoft.core.DBSApproval; import br.com.dbsoft.core.DBSApproval.APPROVAL_STAGE; import br.com.dbsoft.core.DBSSDK; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.io.DBSColumn; import br.com.dbsoft.io.DBSDAO; import br.com.dbsoft.io.DBSResultDataModel; import br.com.dbsoft.message.DBSMessage; import br.com.dbsoft.message.DBSMessage.MESSAGE_TYPE; import br.com.dbsoft.ui.bean.DBSBean; import br.com.dbsoft.ui.bean.crud.DBSCrudBeanEvent.CRUD_EVENT; import br.com.dbsoft.ui.component.DBSUIInput; import br.com.dbsoft.ui.component.DBSUIInputText; import br.com.dbsoft.ui.component.crudform.DBSCrudForm; import br.com.dbsoft.ui.core.DBSFaces; import br.com.dbsoft.util.DBSDate; import br.com.dbsoft.util.DBSIO; import br.com.dbsoft.util.DBSNumber; import br.com.dbsoft.util.DBSObject; /** * @author ricardo.villar * */ /** * @author ricardo.villar * */ public abstract class DBSCrudBean extends DBSBean{ private static final long serialVersionUID = -8550893738791483527L; public static enum EditingMode { NONE ("Not Editing", 0), INSERTING ("Inserting", 1), UPDATING ("Updating", 2), DELETING ("Deleting", 3), APPROVING ("Approving", 4), REPROVING ("Reproving", 5); private String wName; private int wCode; private EditingMode(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingMode get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return INSERTING; case 2: return UPDATING; case 3: return DELETING; case 4: return APPROVING; case 5: return REPROVING; default: return NONE; } } } public static enum EditingStage{ NONE ("None", 0), COMMITTING ("Committing", 1), IGNORING ("Ignoring", 2); private String wName; private int wCode; private EditingStage(String pName, int pCode) { this.wName = pName; this.wCode = pCode; } public String getName() { return wName; } public int getCode() { return wCode; } public static EditingStage get(int pCode) { switch (pCode) { case 0: return NONE; case 1: return COMMITTING; case 2: return IGNORING; default: return NONE; } } } @Inject private Conversation wConversation; private static final long wConversationTimeout = 600000; //10 minutos protected DBSDAO<?> wDAO; private List<IDBSCrudBeanEventsListener> wEventListeners = new ArrayList<IDBSCrudBeanEventsListener>(); private EditingMode wEditingMode = EditingMode.NONE; private EditingStage wEditingStage = EditingStage.NONE; private String wCrudFormFile = ""; private DBSCrudForm wCrudForm; private List<Integer> wSelectedRowsIndexes = new ArrayList<Integer>(); private Collection<DBSColumn> wSavedCurrentColumns = null; private boolean wValueChanged; private int wCopiedRowIndex = -1; private boolean wValidateComponentHasError = false; private boolean wDialogEdit = true; private Boolean wDialogOpened = false; private String wDialogConfirmationEditMessage = "Confirmar a edição?"; private String wDialogConfirmationInsertMessage = "Confirmar a inclusão?"; private String wDialogConfirmationDeleteMessage = "Confirmar a exclusão?"; private String wDialogConfirmationApproveMessage = "Confirmar a aprovação?"; private String wDialogConfirmationReproveMessage = "Confirmar a reprovação?"; private String wDialogIgnoreEditMessage = "Ignorar a edição?"; private String wDialogIgnoreInsertMessage = "Ignorar a inclusão?"; private String wDialogIgnoreDeleteMessage = "Ignorar a exclusão?"; private String wDialogCaption; private Boolean wDialogCloseAfterInsert = false; private Boolean wAllowUpdate = true; private Boolean wAllowInsert = true; private Boolean wAllowDelete = true; private Boolean wAllowRefresh = true; private Boolean wAllowApproval = false; private Boolean wAllowApprove = true; private Boolean wAllowReprove = true; private Boolean wAllowCopy = true; private Boolean wAllowCopyOnUpdate = false; private Integer wApprovalUserStages = 0; private String wColumnNameApprovalStage = null; private String wColumnNameApprovalUserIdRegistered = null; private String wColumnNameApprovalUserIdVerified = null; private String wColumnNameApprovalUserIdConferred = null; private String wColumnNameApprovalUserIdApproved = null; private String wColumnNameApprovalDateApproved = null; private String wColumnNameDateOnInsert = null; private String wColumnNameDateOnUpdate = null; private String wColumnNameUserIdOnInsert = null; private String wColumnNameUserIdOnUpdate = null; private Boolean wRevalidateBeforeCommit = false; private Integer wUserId; private Boolean wMultipleSelection = false; private DBSCrudBean wParentCrudBean = null; private List<DBSCrudBean> wChildrenCrudBean = new ArrayList<DBSCrudBean>(); //Mensagens private DBSMessage wMessageNoRowComitted = new DBSMessage(MESSAGE_TYPE.ERROR,"Erro durante a gravação.\n Nenhum registro foi afetado.\n"); private DBSMessage wMessageOverSize = new DBSMessage(MESSAGE_TYPE.ERROR,"Quantidade de caracteres do texto digitado no campo '%s' ultrapassou a quantidade permitida de %s caracteres. Por favor, diminua o texto digitado."); private DBSMessage wMessageNoChange = new DBSMessage(MESSAGE_TYPE.INFORMATION,"Não houve alteração de informação."); private DBSMessage wMessaggeApprovalSameUserError = new DBSMessage(MESSAGE_TYPE.ERROR,"Não é permitida a aprovação de um registro incluido pelo próprio usuário."); public String getCID(){ return wConversation.getId(); } @Override protected void initializeClass() { pvConversationBegin(); pvFireEventInitialize(); //Finaliza os outros crudbeans antes de inicializar este. // DBSFaces.finalizeDBSBeans(this, false); << Comentado pois os beans passaram a ser criados como ConversationScoped - 12/Ago/2014 } @Override protected void finalizeClass(){ pvFireEventFinalize(); //Exclui os listeners associadao, antes de finalizar wEventListeners.clear(); } public void addEventListener(IDBSCrudBeanEventsListener pEventListener) { if (!wEventListeners.contains(pEventListener)){ wEventListeners.add(pEventListener); } } public void removeEventListener(IDBSCrudBeanEventsListener pEventListener) { if (wEventListeners.contains(pEventListener)){ wEventListeners.remove(pEventListener); } } public <T> void setValue(String pColumnName, Object pColumnValue, Class<T> pValueClass){ T xValue = DBSObject.<T>toClass(pColumnValue, pValueClass); setValue(pColumnName, xValue); } public void setValue(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (!wDialogEdit){ setListValue(pColumnName, pColumnValue); }else{ pvSetValueDAO(pColumnName, pColumnValue); } } public <T> T getValue(String pColumnName){ //Utiliza ListValue para controlar os valores de todas as linhas if (!wDialogEdit){ return getListValue(pColumnName); }else{ return pvGetValue(pColumnName); } } public <T> T getValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClass(getValue(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getValueOriginal(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValueOriginal(pColumnName); }else{ return null; } } public <T> T getValueOriginal(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClass(getValueOriginal(pColumnName), pValueClass); } @SuppressWarnings("unchecked") public <T> T getListValue(String pColumnName){ if (wDAO != null){ return (T) wDAO.getListValue(pColumnName); }else{ return null; } } public <T> T getListValue(String pColumnName, Class<T> pValueClass){ return DBSObject.<T>toClass(getListValue(pColumnName), pValueClass); } private void setListValue(String pColumnName, Object pColumnValue){ if (wDAO != null){ wDAO.setListValue(pColumnName, pColumnValue); } } public boolean getIsListNewRow(){ if (wDAO != null){ return wDAO.getIsNewRow(); }else{ return false; } } public String getListFormattedValue(String pColumnId) throws DBSIOException{return "pColumnId '" + pColumnId + "' desconhecida";} public void crudFormBeforeShowComponent(UIComponent pComponent){ if (wDAO!=null){ //Configura os campos do tipo input if (pComponent instanceof DBSUIInput){ DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) pComponent); if (xColumn!=null){ if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; xInput.setMaxLength(xColumn.getSize()); } } } } } // public void crudFormBeforeInsert(UIComponent pComponent){ // if (wDAO!=null){ //Configura os campos do tipo input // if (pComponent instanceof DBSUIInput){ // DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) pComponent); // if (xColumn!=null){ // if (getEditingMode() == EditingMode.INSERTING && // getEditingStage() == EditingStage.NONE){ // DBSUIInput xInput = (DBSUIInput) pComponent; // //Move o valor do componente para a coluna // if (wDialogEdit){ // setValue(xColumn.getColumnName(), xInput.getValue()); // setValueChanged(false); public void setCrudForm(DBSCrudForm pCrudForm){ wCrudForm = pCrudForm; } /** * Indica a qual crudForm este crudBean esta vinculado.<br/> * @return */ public DBSCrudForm getCrudForm(){ return wCrudForm; } public void crudFormValidateComponent(FacesContext pContext, UIComponent pComponent, Object pValue){ if (wEditingMode!=EditingMode.NONE){ if (wDAO!=null){ if (pValue!=null){ String xSourceId = pContext.getExternalContext().getRequestParameterMap().get(DBSFaces.PARTIAL_SOURCE_PARAM); if (xSourceId !=null && !xSourceId.endsWith(":cancel")){ //TODO verificar se existe uma forma melhor de identificar se foi um cancelamento if (pComponent instanceof DBSUIInputText){ DBSUIInputText xInput = (DBSUIInputText) pComponent; DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression(xInput); if (xColumn!=null){ String xValue = pValue.toString(); if (pValue instanceof Number){ xValue = DBSNumber.getOnlyNumber(xValue); } if (xValue.length() > xColumn.getSize()){ wMessageOverSize.setMessageTextParameters(xInput.getLabel(), xColumn.getSize()); addMessage(wMessageOverSize); wValidateComponentHasError = true; } } } } } } } } public EditingMode getEditingMode() { return wEditingMode; } private synchronized void setEditingMode(EditingMode pEditingMode) { if (wEditingMode != pEditingMode){ wEditingMode = pEditingMode; //Qualquer troca no editingMode, desativa o editingstage setEditingStage(EditingStage.NONE); if (pEditingMode.equals(EditingMode.NONE)){ pvFireEventAfterEdit(); setValueChanged(false); } } } public EditingStage getEditingStage() { return wEditingStage; } private void setEditingStage(EditingStage pEditingStage) { if (wEditingStage != pEditingStage){ // //Limpa as mensagens da fila, caso existam, antes de iniciar o comando para confirmar ou ignorar // if (wEditingStage.equals(EditingStage.NONE)){ // clearMessages(); //Limpa as mensagens da fila, caso existam // if (pEditingStage.equals(EditingStage.NONE)){ // clearMessages(); //Salva novo estado wEditingStage = pEditingStage; } } public void setDialogCaption(String pDialogCaption) {wDialogCaption = pDialogCaption;} public String getDialogCaption() {return wDialogCaption;} public Boolean getDialogOpened() { return wDialogOpened; } private synchronized void setDialogOpened(Boolean pDialogOpened) { if (wDialogEdit){ if (wDialogOpened != pDialogOpened){ wDialogOpened = pDialogOpened; } } } public Boolean getDialogCloseAfterInsert() { return wDialogCloseAfterInsert; } public void setDialogCloseAfterInsert(Boolean pDialogCloseAfterInsert) { wDialogCloseAfterInsert = pDialogCloseAfterInsert; } public Boolean getDialogEdit() {return wDialogEdit;} public void setDialogEdit(Boolean pDialogEdit) {wDialogEdit = pDialogEdit;} public String getDialogConfirmationEditMessage() {return wDialogConfirmationEditMessage;} public void setDialogConfirmationEditMessage(String pDialogConfirmationEditMessage) {wDialogConfirmationEditMessage = pDialogConfirmationEditMessage;} public String getDialogConfirmationInsertMessage() {return wDialogConfirmationInsertMessage;} public void setDialogConfirmationInsertMessage(String pDialogConfirmationInsertMessage) {wDialogConfirmationInsertMessage = pDialogConfirmationInsertMessage;} public String getDialogConfirmationDeleteMessage() {return wDialogConfirmationDeleteMessage;} public void setDialogConfirmationDeleteMessagem(String pDialogConfirmationDeleteMessagem) {wDialogConfirmationDeleteMessage = pDialogConfirmationDeleteMessagem;} public String getDialogConfirmationApproveMessage() {return wDialogConfirmationApproveMessage;} public void setDialogConfirmationApproveMessagem(String pDialogConfirmationApproveMessagem) {wDialogConfirmationApproveMessage = pDialogConfirmationApproveMessagem;} public String getDialogConfirmationReproveMessage() {return wDialogConfirmationReproveMessage;} public void setDialogConfirmationReproveMessagem(String pDialogConfirmationReproveMessagem) {wDialogConfirmationReproveMessage = pDialogConfirmationReproveMessagem;} public String getDialogIgnoreEditMessage() {return wDialogIgnoreEditMessage;} public void setDialogIgnoreEditMessage(String pDialogIgnoreEditMessage) {wDialogIgnoreEditMessage = pDialogIgnoreEditMessage;} public String getDialogIgnoreInsertMessage() {return wDialogIgnoreInsertMessage;} public void setDialogIgnoreInsertMessage(String pDialogIgnoreInsertMessage) {wDialogIgnoreInsertMessage = pDialogIgnoreInsertMessage;} public String getDialogIgnoreDeleteMessage() {return wDialogIgnoreDeleteMessage;} public void setDialogIgnoreDeleteMessage(String pDialogIgnoreDeleteMessage) {wDialogIgnoreDeleteMessage = pDialogIgnoreDeleteMessage;} public DBSResultDataModel getList() throws DBSIOException{ if (wDAO==null){ pvRefreshList(); if (wDAO==null || wDAO.getResultDataModel() == null){ return new DBSResultDataModel(); } clearMessages(); } return wDAO.getResultDataModel(); } /** * Retorna a quantidade de registros da pesquisa principal. * @return * @throws DBSIOException */ public Integer getRowCount() throws DBSIOException{ if (getList() != null){ return getList().getRowCount(); }else{ return 0; } } public Boolean getAllowDelete() throws DBSIOException { return wAllowDelete && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowDelete(Boolean pAllowDelete) {wAllowDelete = pAllowDelete;} public Boolean getAllowUpdate() throws DBSIOException { return wAllowUpdate && pvApprovalUserAllowRegister() && getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public void setAllowUpdate(Boolean pAllowUpdate) {wAllowUpdate = pAllowUpdate;} public Boolean getAllowInsert() { return wAllowInsert && pvApprovalUserAllowRegister(); } public void setAllowInsert(Boolean pAllowInsert) { wAllowInsert = pAllowInsert; setAllowCopy(pAllowInsert); } public Boolean getAllowRefresh() {return wAllowRefresh;} public void setAllowRefresh(Boolean pAllowRefresh) {wAllowRefresh = pAllowRefresh;} public Boolean getMultipleSelection() {return wMultipleSelection;} public void setMultipleSelection(Boolean pMultipleSelection) {wMultipleSelection = pMultipleSelection;} public Boolean getAllowApproval() {return wAllowApproval;} public void setAllowApproval(Boolean pAllowApproval) {wAllowApproval = pAllowApproval;} public Boolean getAllowApprove(){return wAllowApprove;} public void setAllowApprove(Boolean pAllowApprove){wAllowApprove = pAllowApprove;} public Boolean getAllowReprove(){return wAllowReprove;} public void setAllowReprove(Boolean pAllowReprove){wAllowReprove = pAllowReprove;} public Boolean getAllowCopy(){return wAllowCopy;} public void setAllowCopy(Boolean pAllowCopy){wAllowCopy = pAllowCopy;} public Boolean getAllowCopyOnUpdate(){return wAllowCopyOnUpdate;} public void setAllowCopyOnUpdate(Boolean pAllowCopyOnUpdate){wAllowCopyOnUpdate = pAllowCopyOnUpdate;} public APPROVAL_STAGE getApprovalStage() throws DBSIOException { return pvGetApprovalStage(true); } public APPROVAL_STAGE getApprovalStageListValue() throws DBSIOException { return pvGetApprovalStage(false); } public void setApprovalStage(APPROVAL_STAGE pApprovalStage) { setValue(getColumnNameApprovalStage(), pApprovalStage.getCode()); } public APPROVAL_STAGE getApprovalUserNextStage() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserNextStageListValue() throws DBSIOException{ return pvGetApprovalNextUserStage(); } public APPROVAL_STAGE getApprovalUserMaxStage(){ return DBSApproval.getMaxStage(getApprovalUserStages()); } public Integer getApprovalUserStages() {return wApprovalUserStages;} public void setApprovalUserStages(Integer pApprovalUserStages) {wApprovalUserStages = pApprovalUserStages;} public Boolean getIsApprovalStageRegistered() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.REGISTERED; } public Boolean getIsApprovalStageVerified() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.VERIFIED; } public Boolean getIsApprovalStageConferred() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.CONFERRED; } public Boolean getIsApprovalStageApproved() throws DBSIOException{ return getApprovalStage() == APPROVAL_STAGE.APPROVED; } public String getColumnNameApprovalStage() {return wColumnNameApprovalStage;} public void setColumnNameApprovalStage(String pColumnNameApprovalStage) {wColumnNameApprovalStage = pColumnNameApprovalStage;} public String getColumnNameApprovalUserIdRegistered() {return wColumnNameApprovalUserIdRegistered;} public void setColumnNameApprovalUserIdRegistered(String pColumnNameApprovalUserIdRegistered) {wColumnNameApprovalUserIdRegistered = pColumnNameApprovalUserIdRegistered;} public String getColumnNameApprovalUserIdConferred() {return wColumnNameApprovalUserIdConferred;} public void setColumnNameApprovalUserIdConferred(String pColumnNameApprovalUserIdConferred) {wColumnNameApprovalUserIdConferred = pColumnNameApprovalUserIdConferred;} public String getColumnNameApprovalUserIdVerified() {return wColumnNameApprovalUserIdVerified;} public void setColumnNameApprovalUserIdVerified(String pColumnNameApprovalUserIdVerified) {wColumnNameApprovalUserIdVerified = pColumnNameApprovalUserIdVerified;} public String getColumnNameApprovalUserIdApproved() {return wColumnNameApprovalUserIdApproved;} public void setColumnNameApprovalUserIdApproved(String pColumnNameApprovalUserIdApproved) {wColumnNameApprovalUserIdApproved = pColumnNameApprovalUserIdApproved;} public String getColumnNameApprovalDateApproved() {return wColumnNameApprovalDateApproved;} public void setColumnNameApprovalDateApproved(String pColumnNameApprovalDateApproved) {wColumnNameApprovalDateApproved = pColumnNameApprovalDateApproved;} public String getColumnNameDateOnInsert() {return wColumnNameDateOnInsert;} public void setColumnNameDateOnInsert(String pColumnNameDateOnInsert) {wColumnNameDateOnInsert = pColumnNameDateOnInsert;} public String getColumnNameDateOnUpdate() {return wColumnNameDateOnUpdate;} public void setColumnNameDateOnUpdate(String pColumnNameDateOnUpdate) {wColumnNameDateOnUpdate = pColumnNameDateOnUpdate;} public String getColumnNameUserIdOnInsert() {return wColumnNameUserIdOnInsert;} public void setColumnNameUserIdOnInsert(String pColumnNameUserIdOnInsert) {wColumnNameUserIdOnInsert = pColumnNameUserIdOnInsert;} public String getColumnNameUserIdOnUpdate() {return wColumnNameUserIdOnUpdate;} public void setColumnNameUserIdOnUpdate(String pColumnNameUserIdOnUpdate) {wColumnNameUserIdOnUpdate = pColumnNameUserIdOnUpdate;} public Boolean getRevalidateBeforeCommit() {return wRevalidateBeforeCommit;} public void setRevalidateBeforeCommit(Boolean pRevalidateBeforeCommit) {wRevalidateBeforeCommit = pRevalidateBeforeCommit;} public Integer getUserId() {return wUserId;} public void setUserId(Integer pUserId) {wUserId = pUserId;} public void setParentCrudBean(DBSCrudBean pCrudBean) { wParentCrudBean = pCrudBean; if (!pCrudBean.getChildrenCrudBean().contains(this)){ pCrudBean.getChildrenCrudBean().add(this); } } public DBSCrudBean getParentCrudBean() { return wParentCrudBean; } public List<DBSCrudBean> getChildrenCrudBean() { return wChildrenCrudBean; } public String getCrudFormFile() {return wCrudFormFile;} public void setCrudFormFile(String pCrudFormFile) {wCrudFormFile = pCrudFormFile;} public void setValueChanged(Boolean pChanged){ wValueChanged = pChanged; } public boolean getIsValueChanged(){ return wValueChanged; } public Boolean getIsCommitting(){ return (wEditingStage == EditingStage.COMMITTING); } public Boolean getIsUpdating(){ return (wEditingMode == EditingMode.UPDATING); } public Boolean getIsEditing(){ return (wEditingMode != EditingMode.NONE); } public Boolean getIsDeleting(){ return (wEditingMode == EditingMode.DELETING); } public Boolean getIsApproving(){ return (wEditingMode == EditingMode.APPROVING); } public Boolean getIsReproving(){ return (wEditingMode == EditingMode.REPROVING); } // public Boolean getIsApprovalStageApproved(Integer pApprovalStage){ // return DBSApproval.isApproved(pApprovalStage); // public Boolean getIsApprovalStageConferred(Integer pApprovalStage){ // return DBSApproval.isConferred(pApprovalStage); // public Boolean getIsApprovalStageVerified(Integer pApprovalStage){ // return DBSApproval.isVerified(pApprovalStage); // public Boolean getIsApprovalStageRegistered(Integer pApprovalStage){ // return DBSApproval.isRegistered(pApprovalStage); public Boolean getIsApprovingOrReproving(){ return (wEditingMode == EditingMode.APPROVING || wEditingMode == EditingMode.REPROVING); } public Boolean getIsIgnoring(){ return (wEditingStage == EditingStage.IGNORING); } public Boolean getIsFirst(){ if (wDAO != null){ return wDAO.getIsFist(); }else{ return true; } } public Boolean getIsLast(){ if (wDAO != null){ return wDAO.getIsLast(); }else{ return true; } } public Boolean getIsViewing(){ return (wEditingMode == EditingMode.NONE); } public Boolean getIsInserting(){ return (wEditingMode == EditingMode.INSERTING); } public Boolean getIsEditingDisabled(){ if (wAllowApproval || wAllowDelete || wAllowInsert || wAllowUpdate){ return false; } return true; } public void setDisableEditing(){ setAllowApproval(false); setAllowDelete(false); setAllowInsert(false); setAllowUpdate(false); } public Boolean getIsReadOnly(){ if (getIsViewing() || wEditingMode == EditingMode.DELETING){ return true; }else{ return false; } } public Boolean getIsClosed(){ return (!wDialogOpened); } /** * Se tem algumm registro copiado * @return */ public Boolean getIsCopied(){ if (wCopiedRowIndex != -1){ return true; }else{ return false; } } // Methods /** * Retorna lista dos itens selecionados * @return */ public List<Integer> getSelectedRowsIndexes(){ return wSelectedRowsIndexes; } public Boolean getSelected() throws DBSIOException { if (wSelectedRowsIndexes.contains(getList().getRowIndex())){ return true; } return false; } public void setSelected(Boolean pSelectOne) throws DBSIOException { // wDAO.synchronize(); pvSetSelected(pSelectOne); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSetSelected(!pSelectOne); } } public boolean getHasSelected(){ if (wSelectedRowsIndexes != null){ if (wSelectedRowsIndexes.size()>0){ return true; } } return false; } /** * Selectiona todas as linhas que exibidas */ public synchronized String selectAll() throws DBSIOException{ if (!wDialogOpened){ pvSelectAll(); if (pvFireEventBeforeSelect()){ pvFireEventAfterSelect(); }else{ pvSelectAll(); } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String confirmEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ if (wValidateComponentHasError){ wValidateComponentHasError = false; }else{ if ((getIsValueChanged() && getIsDeleting() == false) || getIsDeleting()){ if (pvFireEventBeforeValidate() && pvFireEventValidate()){ setEditingStage(EditingStage.COMMITTING); }else{ if(getIsDeleting() || getIsApprovingOrReproving()){ setEditingMode(EditingMode.NONE); } } }else{ addMessage(wMessageNoChange); } } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } // Methods public synchronized String ignoreEditing() throws DBSIOException{ if (wEditingMode!=EditingMode.NONE){ if (wEditingStage==EditingStage.NONE){ //Disparado eventos antes de ignorar setEditingStage(EditingStage.IGNORING); if (!getIsValueChanged()){ endEditing(true); } }else{ //exibe mensagem de erro de procedimento } }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String endEditing(Boolean pConfirm) throws DBSIOException{ try{ if (pConfirm){ if (wEditingStage!=EditingStage.NONE){ if (wEditingStage==EditingStage.COMMITTING){ //Disparado eventos if (pvFireEventValidate() && pvFireEventBeforeCommit()){ pvFireEventAfterCommit(); pvRefreshList(); pvConfirmEditing(true); }else{ pvConfirmEditing(false); } }else if (wEditingStage==EditingStage.IGNORING){ //Disparado eventos if (pvFireEventBeforeIgnore()){ pvFireEventAfterIgnore(); pvConfirmEditing(true); }else{ pvConfirmEditing(false); } } }else{ //exibe mensagem de erro de procedimento } }else{ setEditingStage(EditingStage.NONE); switch(wEditingMode){ case UPDATING: break; case INSERTING: break; case DELETING: setEditingMode(EditingMode.NONE); view(); break; case APPROVING: setEditingMode(EditingMode.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); close(false); break; default: //Exibe mensagem de erro de procedimento } } }catch(Exception e){ wLogger.error("Crud:" + getDialogCaption() + ":endEditing", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } return DBSFaces.getCurrentView(); } // Methods public synchronized String searchList() throws DBSIOException{ pvRefreshList(); return DBSFaces.getCurrentView(); } public synchronized String refreshList() throws DBSIOException{ pvFireEventInitialize(); return searchList(); } public synchronized String copy() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ wCopiedRowIndex = wDAO.getCurrentRowIndex(); pvFireEventAfterCopy(); } return DBSFaces.getCurrentView(); } /** * Seta os valores atuais com os valores do registro copiado * @throws DBSIOException */ public synchronized String paste() throws DBSIOException{ if (wAllowCopy || wAllowCopyOnUpdate){ if (pvFireEventBeforePaste()){ //Seta o registro atual como sendo o registro copiado wDAO.paste(wCopiedRowIndex); setValueChanged(true); } } return DBSFaces.getCurrentView(); } /** * Exibe todos os itens selecionados */ public synchronized String viewSelection() throws DBSIOException{ if (!wDialogEdit){return DBSFaces.getCurrentView();} //Limpa todas as mensagens que estiverem na fila clearMessages(); if (wDAO.getCurrentRowIndex() != -1){ if (!wDialogOpened){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } } return DBSFaces.getCurrentView(); } /** * Exibe o item selecionado */ public synchronized String view() throws DBSIOException{ if (!wDialogEdit){return DBSFaces.getCurrentView();} //Limpa todas as mensagens que estiverem na fila clearMessages(); if (wDAO.getCurrentRowIndex()!=-1){ if (wEditingStage==EditingStage.NONE){ //Chama evento if (pvFireEventBeforeView()){ setDialogOpened(true); pvFireEventAfterView(); } }else{ //exibir erro de procedimento } }else{ //exibir erro de procedimento } return DBSFaces.getCurrentView(); } /** * Informa com cadastro foi fechado */ public synchronized String close() throws DBSIOException{ return close(true); } /** * Informa que cadastro foi fechado */ public synchronized String close(Boolean pClearMessage) throws DBSIOException{ if (wDialogOpened){ //Dispara evento if (pvFireEventBeforeClose()){ setDialogOpened(false); if (pClearMessage) { clearMessages(); } } //getLastInstance("a"); }else{ //exibe mensagem de erro de procedimento } return DBSFaces.getCurrentView(); } public synchronized String insertSelected() throws DBSIOException{ setDialogCloseAfterInsert(true); view(); copy(); insert(); paste(); wCopiedRowIndex = -1; return DBSFaces.getCurrentView(); } public synchronized String insert() throws DBSIOException{ if (wAllowInsert || wDialogCloseAfterInsert){ if (!wDialogCloseAfterInsert){ clearMessages(); } if (!wDialogEdit && wEditingMode==EditingMode.UPDATING){ pvInsertEmptyRow(); }else{ if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeInsert() && pvFireEventBeforeEdit(EditingMode.INSERTING)){ //Desmarca registros selecionados wSelectedRowsIndexes.clear(); setEditingMode(EditingMode.INSERTING); setDialogOpened(true); }else{ setValueChanged(false); } // if (pvFireEventBeforeEdit(EditingMode.INSERTING)){ // //Desmarca registros selecionados // wSelectedRowsIndexes.clear(); // setEditingMode(EditingMode.INSERTING); // pvMoveBeforeFistRow(); // //Dispara evento BeforeInsert // if (pvFireEventBeforeInsert()){ // setDialogOpened(true); // }else{ // setValueChanged(false); // //exibe mensagem de erro de procedimento } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":insert", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } } return DBSFaces.getCurrentView(); } public synchronized String update() throws DBSIOException{ if (wAllowUpdate){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.UPDATING)){ setEditingMode(EditingMode.UPDATING); pvInsertEmptyRow(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":update", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String delete() throws DBSIOException{ if (wAllowDelete){ clearMessages(); if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.DELETING)){ setEditingMode(EditingMode.DELETING); confirmEditing(); //setEditingStage(EditingStage.COMMITTING); }else{ setValueChanged(false); //setEditingStage(EditingStage.COMMITTING); } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":delete", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String approve() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.APPROVING)){ setEditingMode(EditingMode.APPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":approve", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String reprove() throws DBSIOException{ if (wAllowApproval && wAllowApprove){ if (wUserId== null){ addMessage("UserId", MESSAGE_TYPE.ERROR,"DBSCrudBean: UserId - Não informado!"); return DBSFaces.getCurrentView(); } if (wEditingMode==EditingMode.NONE){ try { if (pvFireEventBeforeEdit(EditingMode.REPROVING)){ setEditingMode(EditingMode.REPROVING); setValueChanged(true); confirmEditing(); }else{ setValueChanged(false); //exibe mensagem de erro de procedimento } } catch (Exception e) { wLogger.error("Crud:" + getDialogCaption() + ":reprove", e); setEditingMode(EditingMode.NONE); DBSIO.throwIOException(e); } }else{ //exibe mensagem de erro de procedimento } } return DBSFaces.getCurrentView(); } public synchronized String moveFirst() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveFirstRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String movePrevious() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.movePreviousRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveNext() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveNextRow(); view(); } return DBSFaces.getCurrentView(); } public synchronized String moveLast() throws DBSIOException{ if (wEditingStage==EditingStage.NONE){ wDAO.moveLastRow(); view(); } return DBSFaces.getCurrentView(); } @Override protected void warningMessageValidated(String pMessageKey, Boolean pIsValidated) throws DBSIOException{ //Se mensagem de warning foi validade.. if (pIsValidated){ confirmEditing(); }else{ if (getEditingMode().equals(EditingMode.DELETING)){ ignoreEditing(); } } } @Override protected boolean openConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.openConnection(); if (wDAO !=null){ wDAO.setConnection(wConnection); } //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); return true; } } return false; } @Override protected void closeConnection() { if (wParentCrudBean == null){ if (!getIsEditing() && !wBrodcastingEvent){ super.closeConnection(); //Configura os crudbean filhos que possam existir pvBroadcastConnection(this); } } } // Abstracted protected abstract void initialize(DBSCrudBeanEvent pEvent) throws DBSIOException; protected void finalize(DBSCrudBeanEvent pEvent){}; protected void beforeClose(DBSCrudBeanEvent pEvent) throws DBSIOException {} ; protected void beforeRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterRefresh(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void afterEdit(DBSCrudBeanEvent pEvent) throws DBSIOException {}; protected void beforeInsert(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void afterView(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforeCommit(DBSCrudBeanEvent pEvent) throws DBSIOException { //Copia dos valores pois podem ter sido alterados durante o beforecommit if (getIsApprovingOrReproving()){ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ pEvent.setCommittedRowCount(wDAO.executeUpdate()); }else{ return; } //Insert/Update/Delete }else{ pvBeforeCommitSetAutomaticColumnsValues(pEvent); if (pEvent.isOk()){ //Insert if(getIsInserting()){ if (wDAO.isAutoIncrementPK()){ wDAO.setValue(wDAO.getPK(), null); } pEvent.setCommittedRowCount(wDAO.executeInsert()); //Update }else if (getIsUpdating()){ if (!wDialogEdit && wDAO.getIsNewRow()){ pEvent.setCommittedRowCount(wDAO.executeInsert()); }else{ pEvent.setCommittedRowCount(wDAO.executeUpdate()); } //Delete }else if(getIsDeleting()){ pEvent.setCommittedRowCount(wDAO.executeDelete()); } } } } protected void afterCommit(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void beforeIgnore(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterIgnore(DBSCrudBeanEvent pEvent){} protected void beforeSelect(DBSCrudBeanEvent pEvent) throws DBSIOException {} protected void afterSelect(DBSCrudBeanEvent pEvent){} protected void beforeValidate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void validate(DBSCrudBeanEvent pEvent) throws DBSIOException{} protected void afterCopy(DBSCrudBeanEvent pEvent) throws DBSIOException{}; protected void beforePaste(DBSCrudBeanEvent pEvent) throws DBSIOException{}; private void pvConversationBegin(){ if (wConversation.isTransient()){ wConversation.begin(); wConversation.setTimeout(wConversationTimeout); } } /** * Atualiza dados da lista e dispara os eventos beforeRefresh e afterRefresh.<br/> * @throws DBSIOException */ private void pvRefreshList() throws DBSIOException{ if (getEditingMode() == EditingMode.UPDATING){ ignoreEditing(); } //Dispara evento para atualizar os dados if (pvFireEventBeforeRefresh()){ //Apaga itens selecionados, se houver. wSelectedRowsIndexes.clear(); pvFireEventAfterRefresh(); } } private void pvConfirmEditing(Boolean pOk) throws DBSIOException{ switch(wEditingMode){ case UPDATING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); pvRestoreValuesOriginal(); pvRefreshList(); view(); }else{ if (pOk){ setEditingMode(EditingMode.NONE); view(); }else{ setEditingStage(EditingStage.NONE); } } break; case INSERTING: if (pOk){ if (wEditingStage==EditingStage.IGNORING || wDialogCloseAfterInsert){ setEditingMode(EditingMode.NONE); close(); }else{ setEditingMode(EditingMode.NONE); insert(); } }else{ setEditingStage(EditingStage.NONE); } break; case DELETING: if (wEditingStage==EditingStage.IGNORING){ setEditingMode(EditingMode.NONE); }else{ wCopiedRowIndex = -1; setEditingMode(EditingMode.NONE); if (pOk){ setDialogOpened(false); } } break; case APPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; case REPROVING: setEditingMode(EditingMode.NONE); setEditingStage(EditingStage.NONE); close(false); break; default: setEditingMode(EditingMode.NONE); //Exibe mensagem de erro de procedimento } } private void pvRestoreValuesOriginal(){ wDAO.restoreValuesOriginal(); } /** * Move para o registro anterior ao primeiro registro. * @throws DBSIOException */ private void pvMoveBeforeFistRow() throws DBSIOException{ wDAO.moveBeforeFirstRow(); } private void pvInsertEmptyRow() throws DBSIOException{ if (wDialogEdit || wEditingMode != EditingMode.UPDATING || !wAllowInsert){ return; } wDAO.insertEmptyRow(); pvFireEventBeforeInsert(); } private DBSColumn pvGetDAOColumnFromInputValueExpression(DBSUIInput pInput){ String xColumnName = DBSFaces.getAttibuteNameFromInputValueExpression(pInput).toLowerCase(); if (xColumnName!=null && !xColumnName.equals("")){ //Retira do os prefixos controlados pelo sistema para encontrar o nome da coluna if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_CRUD.getName().length()); }else if (xColumnName.startsWith(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName())){ xColumnName = xColumnName.substring(DBSSDK.UI.ID_PREFIX.FIELD_AUX.getName().length()); } if (wDAO.containsColumn(xColumnName)){ return wDAO.getColumn(xColumnName); } } return null; } private void pvBroadcastConnection(DBSCrudBean pBean){ for (DBSCrudBean xChildBean:pBean.getChildrenCrudBean()){ Connection xCn = xChildBean.getConnection(); DBSIO.closeConnection(xCn); xChildBean.setConnection(pBean.getConnection()); //Procura pelos netos pvBroadcastConnection(xChildBean); } } /** * Salva indice do linha selacionada * @param pSelectOne * @throws DBSIOException */ private void pvSetSelected(Boolean pSelectOne) throws DBSIOException{ Integer xRowIndex = getList().getRowIndex(); if (pSelectOne){ if (!wDialogEdit){ setValueChanged(true); } if (!wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.add(xRowIndex); } }else{ if (wSelectedRowsIndexes.contains(xRowIndex)){ wSelectedRowsIndexes.remove(xRowIndex); } } } private void pvSelectAll() throws DBSIOException{ for (Integer xX = 0; xX < getList().getRowCount(); xX++){ if (wSelectedRowsIndexes.contains(xX)){ wSelectedRowsIndexes.remove(xX); }else{ wSelectedRowsIndexes.add(xX); } } } /** * Seta o valor da coluna no DAO * @param pColumnName * @param pColumnValue */ private void pvSetValueDAO(String pColumnName, Object pColumnValue){ //Utiliza ListValue para controlar os valores de todas as linhas if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ Object xOldValue = pvGetValue(pColumnName); if (pColumnValue != null){ xOldValue = DBSObject.toClass(xOldValue, pColumnValue.getClass()); } if(!DBSObject.getNotNull(xOldValue,"").toString().equals(DBSObject.getNotNull(pColumnValue,"").toString())){ if (getEditingMode() == EditingMode.INSERTING && getDialogOpened()){ wLogger.info("ALTERADO:" + pColumnName + "[" + DBSObject.getNotNull(xOldValue,"") + "] para [" + DBSObject.getNotNull(pColumnValue,"") + "]"); } //marca como valor alterado setValueChanged(true); wDAO.setValue(pColumnName, pColumnValue); } } } /** * Retorna valor da coluna a partir do DAO * @param pColumnName * @return */ @SuppressWarnings("unchecked") private <T> T pvGetValue(String pColumnName){ //Se existir registro corrente if (wDAO != null && (wDAO.getColumns().size() > 0 || wDAO.getCommandColumns().size() > 0)){ return (T) wDAO.getValue(pColumnName); }else{ return null; } } private APPROVAL_STAGE pvGetApprovalStage(boolean pFromValue){ if (!getAllowApproval()){ return APPROVAL_STAGE.REGISTERED; } APPROVAL_STAGE xStage; if (pFromValue){ xStage = APPROVAL_STAGE.get(getValue(getColumnNameApprovalStage())); }else{ xStage = APPROVAL_STAGE.get(getListValue(getColumnNameApprovalStage())); } if (xStage==null){ xStage = APPROVAL_STAGE.REGISTERED; } return xStage; } private boolean pvApprovalUserAllowRegister(){ if (getAllowApproval() && !DBSApproval.isRegistered(getApprovalUserStages())){ return false; } return true; } private Integer pvGetApprovalNextUserStages() throws DBSIOException{ return DBSApproval.getNextUserStages(getApprovalStage(), getApprovalUserStages()); } private APPROVAL_STAGE pvGetApprovalNextUserStage() throws DBSIOException{ return DBSApproval.getMaxStage(pvGetApprovalNextUserStages()); } private void pvBeforeCommitSetAutomaticColumnsValues(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; //Delete if(getIsDeleting()){ return; } //Configura os valores das assinaturas se assinatura estive habilitada. if (getAllowApproval()){ pvBeforeCommitSetAutomaticColumnsValuesApproval(pEvent); } //Insert if(getIsInserting()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnInsert()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnInsert()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } //Update }else if (getIsUpdating()){ xColumn = wDAO.getCommandColumn(getColumnNameUserIdOnUpdate()); if (xColumn!=null){ xColumn.setValue(getUserId()); } xColumn = wDAO.getCommandColumn(getColumnNameDateOnUpdate()); if (xColumn!=null){ xColumn.setValue(DBSDate.getNowDateTime()); } } } private void pvBeforeCommitSetAutomaticColumnsValuesApproval(DBSCrudBeanEvent pEvent) throws DBSIOException{ DBSColumn xColumn = null; APPROVAL_STAGE xApprovalNextStage = null; Integer xUserId = null; Timestamp xApprovalDate = null; Integer xApprovalNextUserStages = null; xUserId = getUserId(); xApprovalDate = DBSDate.getNowTimestamp(); if (getIsApproving()){ xApprovalNextUserStages = pvGetApprovalNextUserStages(); xApprovalNextStage = pvGetApprovalNextUserStage(); }else if (getIsReproving()){ xApprovalNextUserStages = DBSApproval.getApprovalStage(false, true, true, true); xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xUserId = null; xApprovalDate = null; }else if(getIsInserting() || getIsUpdating()){ xApprovalNextStage = APPROVAL_STAGE.REGISTERED; xApprovalNextUserStages = APPROVAL_STAGE.REGISTERED.getCode(); } if (xApprovalNextStage==APPROVAL_STAGE.REGISTERED){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){xColumn.setValue(getUserId());} }else{ if (DBSApproval.isConferred(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdConferred()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isVerified(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdVerified()); if (xColumn!=null){xColumn.setValue(xUserId);} } if (DBSApproval.isApproved(xApprovalNextUserStages)){ xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdRegistered()); if (xColumn!=null){ if (DBSNumber.toInteger(xColumn.getValue()).equals(xUserId)){ addMessage(wMessaggeApprovalSameUserError); pEvent.setOk(false); return; } } xColumn = wDAO.getCommandColumn(getColumnNameApprovalUserIdApproved()); if (xColumn!=null){xColumn.setValue(xUserId);} xColumn = wDAO.getCommandColumn(getColumnNameApprovalDateApproved()); if (xColumn!=null){xColumn.setValue(xApprovalDate);} } } setApprovalStage(xApprovalNextStage); } // private void pvBeforeInsertResetValues(UIComponent pComponent){ // if (pComponent==null){return;} // Iterator<UIComponent> xI = pComponent.getFacetsAndChildren(); // if (wDAO!=null){ // while (xI.hasNext()){ // UIComponent xC = xI.next(); // //Configura os campos do tipo input // if (xC instanceof DBSUIInput){ // DBSColumn xColumn = pvGetDAOColumnFromInputValueExpression((DBSUIInput) xC); // if (xColumn!=null){ // if (getEditingMode() == EditingMode.INSERTING && // getEditingStage() == EditingStage.NONE){ // DBSUIInput xInput = (DBSUIInput) xC; // //Move o valor do componente para a coluna // if (wDialogEdit){ // setValue(xColumn.getColumnName(), xInput.getValue()); // setValueChanged(false); // }else{ // //Chamada recursiva // pvBeforeInsertResetValues(xC); private void pvCurrentRowSave(){ wSavedCurrentColumns = null; if (wDAO != null){ wSavedCurrentColumns = wDAO.getCommandColumns(); //utiliza as colunas da query if (wDAO.getCommandColumns() == null || wDAO.getCommandColumns().size() == 0){ wSavedCurrentColumns = wDAO.getColumns(); } } } private void pvCurrentRowRestore() throws DBSIOException{ boolean xOk; Object xSavedValue = null; Object xCurrentValue = null; BigDecimal xSavedNumberValue = null; BigDecimal xCurrentNumberValue = null; boolean xEqual; if (wDAO != null && wSavedCurrentColumns !=null && wSavedCurrentColumns.size() > 0 && wDAO.getResultDataModel() != null){ DBSResultDataModel xQueryRows = wDAO.getResultDataModel(); for (int xRowIndex = 0; xRowIndex <= xQueryRows.getRowCount()-1; xRowIndex++){ xQueryRows.setRowIndex(xRowIndex); xOk = true; //Loop por todas as colunas da linha da query for (String xQueryColumnName:xQueryRows.getRowData().keySet()){ Object xQueryColumnValue = xQueryRows.getRowData().get(xQueryColumnName); //Procura pelo coluna que possua o mesmo nome for (DBSColumn xColumnSaved: wSavedCurrentColumns){ if (xColumnSaved.getColumnName().equalsIgnoreCase(xQueryColumnName)){ xSavedValue = DBSObject.getNotNull(xColumnSaved.getValue(),""); xCurrentValue = DBSObject.getNotNull(xQueryColumnValue,""); xEqual = false; if (xCurrentValue == null && xSavedValue == null){ xEqual = true; }else if (xCurrentValue instanceof Number){ xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); if (xSavedValue instanceof Number){ xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); } if (xSavedNumberValue != null && xCurrentNumberValue != null){ if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ xEqual = true; } } }else{ xEqual = xSavedValue.equals(xCurrentValue); } if (!xEqual){ xOk = false; } break; } } if (!xOk){ break; } } if (xOk){ return; } } if (wDAO != null){ wDAO.moveFirstRow(); } } } // private void pvCurrentRowRestore() throws DBSIOException{ // boolean xOk; // Integer xRowIndex; // Object xSavedValue = null; // Object xCurrentValue = null; // BigDecimal xSavedNumberValue = null; // BigDecimal xCurrentNumberValue = null; // boolean xEqual; // if (wDAO != null // && wSavedCurrentColumns !=null // && wSavedCurrentColumns.size() > 0 // && wDAO.getResultDataModel() != null){ // //Recupera todas as linhas // Iterator<SortedMap<String, Object>> xIR = wDAO.getResultDataModel().iterator(); // xRowIndex = -1; // while (xIR.hasNext()){ // xOk = true; // xRowIndex++; // //Recupera todas as colunas da linha // SortedMap<String, Object> xColumns = xIR.next(); // //Loop por todas as colunas da linha // for (Entry<String, Object> xC:xColumns.entrySet()){ // Iterator<DBSColumn> xIS = wSavedCurrentColumns.iterator(); // //Procura pelo coluna que possua o mesmo nome // while (xIS.hasNext()){ // DBSColumn xSC = xIS.next(); // if (xSC.getColumnName().equalsIgnoreCase(xC.getKey())){ // xSavedValue = DBSObject.getNotNull(xSC.getValue(),""); // xCurrentValue = DBSObject.getNotNull(xC.getValue(),""); // xEqual = false; // if (xCurrentValue == null // && xSavedValue == null){ // xEqual = true; // }else if (xCurrentValue instanceof Number){ // xCurrentNumberValue = DBSNumber.toBigDecimal(xCurrentValue); // if (xSavedValue instanceof Number){ // xSavedNumberValue = DBSNumber.toBigDecimal(xSavedValue); // if (xSavedNumberValue != null // && xCurrentNumberValue != null){ // if (xCurrentNumberValue.compareTo(xSavedNumberValue) == 0){ // xEqual = true; // }else{ // xEqual = xSavedValue.equals(xCurrentValue); // if (!xEqual){ // xOk = false; // break; // if (!xOk){ // break; // if (xOk){ // wDAO.setCurrentRowIndex(xRowIndex); // return; //// if (wParentCrudBean == null){ // if (wDAO != null){ // wDAO.moveFirstRow(); private void pvFireEventInitialize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.INITIALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private void pvFireEventFinalize(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.FINALIZE, getEditingMode()); try { pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventFinalize",e); } } private boolean pvFireEventBeforeClose(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_CLOSE, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeClose",e); } return xE.isOk(); } private boolean pvFireEventBeforeView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VIEW, getEditingMode()); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeView",e); } return xE.isOk(); } private void pvFireEventAfterView(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_VIEW, getEditingMode()); setValueChanged(false); try { pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterView",e); } } private boolean pvFireEventBeforeInsert() throws DBSIOException{ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_INSERT, getEditingMode()); openConnection(); pvMoveBeforeFistRow(); // pvBeforeInsertResetValues(wCrudForm); try { pvBroadcastEvent(xE, true, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeInsert",e); } setValueChanged(false); return xE.isOk(); } private boolean pvFireEventBeforeEdit(EditingMode pEditingMode){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_EDIT, pEditingMode); setValueChanged(false); try{ pvBroadcastEvent(xE, false, true, false); return xE.isOk(); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeEdit",e); } return xE.isOk(); } private boolean pvFireEventAfterEdit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_EDIT, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterEdir",e); } return xE.isOk(); } private boolean pvFireEventBeforeRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeRefresh",e); } return xE.isOk(); } private void pvFireEventAfterRefresh(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_REFRESH, getEditingMode()); try{ pvBroadcastEvent(xE, true, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventInitialize",e); } } private boolean pvFireEventBeforeIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterIgnore(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_IGNORE, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private boolean pvFireEventBeforeValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || !wDialogEdit){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não há registro selecionado."); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeValidate",e); } return xE.isOk(); } private boolean pvFireEventValidate(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.VALIDATE, getEditingMode()); try{ if (getIsApprovingOrReproving() || !wDialogEdit){ if (getHasSelected()){ wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); pvBroadcastEvent(xE, false, false, false); if (!xE.isOk()){ if (getIsApprovingOrReproving()){ addMessage("erroassinatura", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a edição de todos os itens selecionados. Procure efetuar a edição individualmente para identificar o registro com problema."); break; }else{ addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a edição de todos os itens selecionados. Procure efetuar a edição individualmente para identificar o registro com problema."); break; } } } }else{ xE.setOk(false); addMessage("erroselecao", MESSAGE_TYPE.ERROR,"Não há registro selecionado."); } }else{ pvBroadcastEvent(xE, false, false, false); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventValidate",e); } return xE.isOk(); } private boolean pvFireEventBeforeCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_COMMIT, getEditingMode()); String xErrorMsg = null; //Chame o metodo(evento) local para quando esta classe for extendida try { //Zera a quantidade de registros afetados xE.setCommittedRowCount(0); wDAO.setConnection(wConnection); //Se for o crud principal if (wParentCrudBean == null){ DBSIO.beginTrans(wConnection); } if (getIsApprovingOrReproving() || !wDialogEdit){ if (getHasSelected()){ int xCount = 0; wDAO.setCurrentRowIndex(-1); for (Integer xRowIndex : wSelectedRowsIndexes){ wDAO.setCurrentRowIndex(xRowIndex); if (!wDialogEdit){ wDAO.setExecuteOnlyChangedValues(false); } pvBroadcastEvent(xE, false, false, false); xCount += xE.getCommittedRowCount(); if (!xE.isOk()){ break; } } //Ignora assinatura caso quantidade todal de registros afetados seja inferior a quantidade de itens selectionados if (xCount < wSelectedRowsIndexes.size()){ xE.setCommittedRowCount(0); xE.setOk(false); addMessage("erroassinatura", MESSAGE_TYPE.ERROR,"Não foi possível efetuar a assinatura de todos os itens selecionados. Procure efetuar a assinatura individualmente para identificar o registro com problema."); }else{ xE.setCommittedRowCount(xCount); } } }else{ pvBroadcastEvent(xE, false, false, false); } if (!wDialogMessages.hasMessages() && (!xE.isOk() || xE.getCommittedRowCount().equals(0))){ xE.setOk(false); addMessage(wMessageNoRowComitted); } //Se for o crud principal if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, xE.isOk()); } } catch (Exception e) { xE.setOk(false); try { //Se for o crud principal if (wParentCrudBean == null){ DBSIO.endTrans(wConnection, false); } if (e instanceof DBSIOException){ DBSIOException xDBException = (DBSIOException) e; xErrorMsg = e.getMessage(); if (xDBException.isIntegrityConstraint()){ clearMessages(); // addMessage("integridate", MESSAGE_TYPE.ERROR, xDBException.getLocalizedMessage()); wMessageError.setMessageText(xDBException.getLocalizedMessage()); wMessageError.setMessageTooltip(xErrorMsg); addMessage(wMessageError); }else{ wLogger.error("EventBeforeCommit", e); } } } catch (DBSIOException e1) { xErrorMsg = e1.getMessage(); } wMessageNoRowComitted.setMessageTooltip(xErrorMsg); addMessage(wMessageNoRowComitted); } return xE.isOk(); } private void pvFireEventAfterCommit(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COMMIT, getEditingMode()); try{ pvBroadcastEvent(xE, false, false, false); if (wParentCrudBean!=null){ wParentCrudBean.setValueChanged(true); } } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCommit",e); } } private boolean pvFireEventBeforeSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforeIgnore",e); } return xE.isOk(); } private void pvFireEventAfterSelect(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_SELECT, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterIgnore",e); } } private void pvFireEventAfterCopy(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.AFTER_COPY, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventAfterCopy",e); } } /** * Disparado antes do paste. * @return */ private boolean pvFireEventBeforePaste(){ DBSCrudBeanEvent xE = new DBSCrudBeanEvent(this, CRUD_EVENT.BEFORE_PASTE, getEditingMode()); try{ pvBroadcastEvent(xE, false, true, true); } catch (Exception e) { xE.setOk(false); wLogger.error("EventBeforePaste",e); } return xE.isOk(); } private void pvBroadcastEvent(DBSCrudBeanEvent pEvent, boolean pInvokeChildren, boolean pOpenConnection, boolean pCloseConnection) throws Exception { try{ if (pOpenConnection){ openConnection(); } wBrodcastingEvent = true; pvFireEventLocal(pEvent); if (pInvokeChildren){ pvFireEventChildren(pEvent); } pvFireEventListeners(pEvent); }catch(DBSIOException e){ wMessageError.setMessageText(e.getLocalizedMessage()); wMessageError.setMessageTooltip(e.getOriginalException().getLocalizedMessage()); if (!DBSObject.isEmpty(e.getCause())){ wMessageError.setMessageTooltip(e.getCause().getMessage() + "<br/>" + e.getMessage()); } addMessage(wMessageError); pEvent.setOk(false); // wLogger.error(pEvent.getEvent().toString(), e); }catch(Exception e){ String xStr = pEvent.getEvent().toString() + ":" + DBSObject.getNotNull(this.getDialogCaption(),"") + ":"; if (e.getLocalizedMessage()!=null){ xStr = xStr + e.getLocalizedMessage(); }else{ xStr = xStr + e.getClass(); } wMessageError.setMessageTextParameters(xStr); addMessage(wMessageError); pEvent.setOk(false); wLogger.error(pEvent.getEvent().toString(), e); throw e; }finally{ wBrodcastingEvent = false; if (pCloseConnection || !pEvent.isOk()){ closeConnection(); } } } private void pvFireEventLocal(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ switch (pEvent.getEvent()) { case INITIALIZE: initialize(pEvent); break; case FINALIZE: finalize(pEvent); break; case BEFORE_CLOSE: beforeClose(pEvent); break; case BEFORE_VIEW: beforeView(pEvent); break; case AFTER_VIEW: afterView(pEvent); break; case BEFORE_INSERT: beforeInsert(pEvent); break; case BEFORE_REFRESH: pvCurrentRowSave(); beforeRefresh(pEvent); pvCurrentRowRestore(); break; case AFTER_REFRESH: afterRefresh(pEvent); break; case BEFORE_COMMIT: beforeCommit(pEvent); break; case AFTER_COMMIT: afterCommit(pEvent); break; case BEFORE_IGNORE: beforeIgnore(pEvent); break; case AFTER_IGNORE: afterIgnore(pEvent); break; case BEFORE_EDIT: beforeEdit(pEvent); break; case AFTER_EDIT: afterEdit(pEvent); break; case BEFORE_SELECT: beforeSelect(pEvent); break; case AFTER_SELECT: afterSelect(pEvent); break; case BEFORE_VALIDATE: beforeValidate(pEvent); break; case VALIDATE: validate(pEvent); break; case AFTER_COPY: afterCopy(pEvent); break; case BEFORE_PASTE: beforePaste(pEvent); break; default: break; } } } private void pvFireEventChildren(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ for (DBSCrudBean xBean:wChildrenCrudBean){ if (pEvent.getEvent() == CRUD_EVENT.BEFORE_VIEW || pEvent.getEvent() == CRUD_EVENT.BEFORE_INSERT){ pvRefreshList(); } switch (pEvent.getEvent()) { case INITIALIZE: xBean.initialize(pEvent); break; case FINALIZE: xBean.finalize(pEvent); break; case BEFORE_CLOSE: xBean.beforeClose(pEvent); break; case BEFORE_VIEW: xBean.beforeView(pEvent); break; case AFTER_VIEW: xBean.afterView(pEvent); break; case BEFORE_INSERT: xBean.beforeInsert(pEvent); break; case BEFORE_REFRESH: xBean.beforeRefresh(pEvent); break; case AFTER_REFRESH: xBean.afterRefresh(pEvent); break; case BEFORE_COMMIT: xBean.beforeCommit(pEvent); break; case AFTER_COMMIT: xBean.afterCommit(pEvent); break; case BEFORE_IGNORE: xBean.beforeIgnore(pEvent); break; case AFTER_IGNORE: xBean.afterIgnore(pEvent); break; case BEFORE_EDIT: xBean.beforeEdit(pEvent); break; case AFTER_EDIT: xBean.afterEdit(pEvent); break; case BEFORE_SELECT: xBean.beforeSelect(pEvent); break; case AFTER_SELECT: xBean.afterSelect(pEvent); break; case BEFORE_VALIDATE: xBean.beforeValidate(pEvent); break; case VALIDATE: xBean.validate(pEvent); break; case AFTER_COPY: xBean.afterCopy(pEvent); break; case BEFORE_PASTE: xBean.beforePaste(pEvent); break; default: break; } if (!pEvent.isOk()){ break; } } } } private void pvFireEventListeners(DBSCrudBeanEvent pEvent) throws DBSIOException{ if (pEvent.isOk()){ for (int xX=0; xX<wEventListeners.size(); xX++){ switch (pEvent.getEvent()) { case INITIALIZE: wEventListeners.get(xX).initialize(pEvent); break; case FINALIZE: wEventListeners.get(xX).finalize(pEvent); break; case BEFORE_CLOSE: wEventListeners.get(xX).beforeClose(pEvent); break; case BEFORE_VIEW: wEventListeners.get(xX).beforeView(pEvent); break; case AFTER_VIEW: wEventListeners.get(xX).afterView(pEvent); break; case BEFORE_REFRESH: wEventListeners.get(xX).beforeRefresh(pEvent); break; case BEFORE_INSERT: wEventListeners.get(xX).beforeInsert(pEvent); break; case AFTER_REFRESH: wEventListeners.get(xX).afterRefresh(pEvent); break; case BEFORE_COMMIT: wEventListeners.get(xX).beforeCommit(pEvent); break; case AFTER_COMMIT: wEventListeners.get(xX).afterCommit(pEvent); break; case BEFORE_IGNORE: wEventListeners.get(xX).beforeIgnore(pEvent); break; case AFTER_IGNORE: wEventListeners.get(xX).afterIgnore(pEvent); break; case BEFORE_EDIT: wEventListeners.get(xX).beforeEdit(pEvent); break; case AFTER_EDIT: wEventListeners.get(xX).afterEdit(pEvent); break; case BEFORE_SELECT: wEventListeners.get(xX).beforeSelect(pEvent); break; case AFTER_SELECT: wEventListeners.get(xX).afterSelect(pEvent); break; case BEFORE_VALIDATE: wEventListeners.get(xX).beforeValidate(pEvent); break; case VALIDATE: wEventListeners.get(xX).validate(pEvent); break; case AFTER_COPY: wEventListeners.get(xX).afterCopy(pEvent); break; case BEFORE_PASTE: wEventListeners.get(xX).beforePaste(pEvent); break; default: break; } //Sa do loop se encontrar erro if (!pEvent.isOk()){ break; } } } } }
package br.gov.servicos.editor.servicos; import lombok.SneakyThrows; import lombok.experimental.FieldDefaults; import lombok.extern.slf4j.Slf4j; import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.TextProgressMonitor; import org.eclipse.jgit.merge.MergeStrategy; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.transport.RefSpec; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.User; import org.springframework.stereotype.Component; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; import static java.lang.String.format; import static java.nio.charset.Charset.defaultCharset; import static java.util.Optional.empty; import static java.util.Optional.of; import static java.util.stream.Collectors.*; import static lombok.AccessLevel.PRIVATE; import static org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode.NOTRACK; import static org.eclipse.jgit.lib.Constants.*; @Slf4j @Component @FieldDefaults(level = PRIVATE, makeFinal = true) public class Cartas { File repositorioCartasLocal; Path v3; boolean fazerPush; @Autowired public Cartas(File repositorioCartasLocal, @Value("${flags.git.push}") boolean fazerPush) { this.repositorioCartasLocal = repositorioCartasLocal; this.fazerPush = fazerPush; this.v3 = Paths.get(repositorioCartasLocal.getAbsolutePath(), "cartas-servico", "v3", "servicos"); } @SneakyThrows public Optional<String> conteudoServicoV1(String id) { return conteudoServico(id, leitorDeConteudo(id, "v1")); } @SneakyThrows public Optional<String> conteudoServicoV3(String id) { return conteudoServico(id, leitorDeConteudo(id, "v3")); } public Optional<String> conteudoServico(String id, Supplier<Optional<String>> leitor) { return executaNoBranchDoServico(id, leitor); } public Supplier<Optional<String>> leitorDeConteudo(String id, String versao) { return () -> { File arquivo = Paths.get(repositorioCartasLocal.getAbsolutePath(), "cartas-servico", versao, "servicos", id + ".xml").toFile(); if (arquivo.exists()) { log.info("Arquivo {} encontrado", arquivo); return ler(arquivo); } log.info("Arquivo {} não encontrado", arquivo); return empty(); }; } public Optional<Metadados> ultimaRevisaoV1(String id) { return comRepositorioAberto(git -> metadados(git, id, xmlServico(id, "v1"))); } public Optional<Metadados> ultimaRevisaoV3(String id) { return comRepositorioAberto(git -> metadados(git, id, xmlServico(id, "v3"))); } public Iterable<Metadados> listar() { return comRepositorioAberto(git -> todosServicos().stream() .map(p -> metadados(git, p.getKey(), p.getValue())) .map(Optional::get) .filter(Objects::nonNull) .collect(toList())); } @SneakyThrows public void excluir(String id, User usuario) { comRepositorioAberto(git -> { pull(git); try { executaNoBranchDoServico(id, () -> { commit(git, "Serviço deletado", usuario, excluirCarta(git, "v3", id), excluirCarta(git, "v2", id), excluirCarta(git, "v1", id)); return null; }); return null; } finally { push(git, id); } }); } @SneakyThrows private Path excluirCarta(Git git, String versao, String id) { Path caminho = caminhoAbsoluto(versao, id); if (!caminho.toFile().exists()) return null; git.rm().addFilepattern(caminhoRelativo(caminho)).call(); log.debug("git rm {}", caminho); return caminho; } private Set<Map.Entry<String, Path>> todosServicos() { FilenameFilter filter = (x, name) -> name.endsWith(".xml"); Function<Path, String> getId = f -> f.toFile().getName().replaceAll(".xml$", ""); Function<Path, Map<String, Path>> indexaServicos = f -> Arrays.asList(f.toFile().listFiles(filter)) .stream() .map(File::toPath) .collect(toMap(getId, x -> x)); Map<String, Path> mapaServicos = indexaServicos.apply(v3); return mapaServicos.entrySet(); } @SneakyThrows private Optional<Metadados> metadados(Git git, String id, Path f) { RevCommit rev = Optional.ofNullable(git.getRepository().getRef(R_HEADS + id)) .map(o -> { try { return git.log().add(o.getObjectId()).setMaxCount(1).call().iterator().next(); } catch (Throwable t) { throw new RuntimeException(t); } }) .orElse(git.log().addPath(caminhoRelativo(f)).setMaxCount(1).call().iterator().next()); return Optional.ofNullable(rev) .map(c -> new Metadados() .withId(id) .withRevisao(c.getId().getName()) .withAutor(c.getAuthorIdent().getName()) .withHorario(c.getAuthorIdent().getWhen())); } @SneakyThrows private Optional<String> ler(File arquivo) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(arquivo), defaultCharset()))) { return of(reader.lines().collect(joining("\n"))); } } @SneakyThrows public void salvarServicoV3(String id, String doc, User usuario) { comRepositorioAberto(git -> { pull(git); try { return executaNoBranchDoServico(id, () -> { Path caminho = caminhoAbsoluto("v3", id); Path dir = caminho.getParent(); if (dir.toFile().mkdirs()) { log.debug("Diretório {} não existia e foi criado", dir); } else { log.debug("Diretório {} já existia e não precisou ser criado", dir); } String mensagem = format("%s '%s'", caminho.toFile().exists() ? "Altera" : "Cria", id); escreveV3(doc, caminho); add(git, caminho); commit(git, mensagem, usuario, caminho); return null; }); } finally { push(git, id); } }); } private Path caminhoAbsoluto(String versao, String id) { return Paths.get(repositorioCartasLocal.getAbsolutePath(), "cartas-servico", versao, "servicos", id + ".xml"); } @SneakyThrows private void push(Git git, String id) { log.info("git push: {} ({})", git.getRepository().getBranch(), git.getRepository().getRepositoryState()); if (fazerPush && !id.equals("novo")) { git.push() .setRemote(DEFAULT_REMOTE_NAME) .setRefSpecs(new RefSpec(id + ":" + id)) .setProgressMonitor(new TextProgressMonitor()) .call(); } else { log.info("Envio de alterações ao Github desligado (FLAGS_GIT_PUSH=false)"); } } @SneakyThrows private void pull(Git git) { log.info("git pull: {} ({})", git.getRepository().getBranch(), git.getRepository().getRepositoryState()); git.pull() .setRebase(true) .setStrategy(MergeStrategy.THEIRS) .setProgressMonitor(new TextProgressMonitor()) .call(); } @SneakyThrows private void commit(Git git, String mensagem, User usuario, Path... caminhos) { PersonIdent ident = new PersonIdent(usuario.getUsername(), "servicos@planejamento.gov.br"); log.debug("git commit: {} ({}): '{}', {}, {}", git.getRepository().getBranch(), git.getRepository().getRepositoryState(), mensagem, ident, caminhos ); try { CommitCommand cmd = git.commit() .setMessage(mensagem) .setCommitter(ident) .setAuthor(ident); Arrays.asList(caminhos) .stream() .filter(Objects::nonNull) .forEach(p -> cmd.setOnly(caminhoRelativo(p))); cmd.call(); } catch (JGitInternalException e) { if (e.getMessage().equals(JGitText.get().emptyCommit)) { log.info("{} não sofreu alterações", caminhos); } else { throw e; } } } @SneakyThrows private void add(Git git, Path path) { String pattern = caminhoRelativo(path); log.debug("git add: {} ({})", git.getRepository().getBranch(), git.getRepository().getRepositoryState(), pattern); git.add() .addFilepattern(pattern) .call(); } private String caminhoRelativo(Path path) { return repositorioCartasLocal.toPath().relativize(path).toString(); } @SneakyThrows private <T> T comRepositorioAberto(Function<Git, T> fn) { try (Git git = Git.open(repositorioCartasLocal)) { synchronized (Cartas.class) { return fn.apply(git); } } } @SneakyThrows private <T> T executaNoBranchDoServico(String id, Supplier<T> supplier) { return comRepositorioAberto(git -> { checkout(git, id); try { return supplier.get(); } finally { checkoutMaster(git); } }); } @SneakyThrows private void checkoutMaster(Git git) { log.debug("git checkout master: {} ({})", git.getRepository().getBranch(), git.getRepository().getRepositoryState()); git.checkout().setName(MASTER).call(); } @SneakyThrows private void checkout(Git git, String id) { log.debug("git checkout: {} ({})", git.getRepository().getBranch(), git.getRepository().getRepositoryState(), id); git.checkout() .setName(id) .setStartPoint(R_HEADS + MASTER) .setUpstreamMode(NOTRACK) .setCreateBranch(!branchExiste(git, id)) .call(); } @SneakyThrows private boolean branchExiste(Git git, String id) { boolean resultado = git .branchList() .call() .stream() .anyMatch(b -> b.getName().equals(R_HEADS + id)); log.debug("git branch {} já existe? {}", id, resultado); return resultado; } private Path xmlServico(String id, String versao) { return Paths.get(repositorioCartasLocal.getAbsolutePath(), "cartas-servico", versao, "servicos", id + ".xml"); } @SneakyThrows private void escreveV3(String document, Path arquivo) { try (Writer writer = new OutputStreamWriter(new FileOutputStream(arquivo.toFile()), "UTF-8")) { writer.write(document); } log.debug("Arquivo '{}' modificado", arquivo.getFileName()); } }
package cat.nyaa.nyaacore.utils; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.io.BaseEncoding; import com.google.common.io.ByteStreams; import com.mojang.datafixers.DSL; import com.mojang.datafixers.DataFixer; import com.mojang.datafixers.Dynamic; import net.minecraft.server.v1_13_R2.*; import org.bukkit.Bukkit; import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack; import org.bukkit.inventory.ItemStack; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.zip.DeflaterInputStream; import java.util.zip.InflaterInputStream; public final class ItemStackUtils { private static final String NYAACORE_ITEMSTACK_DATAVERSION_KEY = "nyaacore_itemstack_dataversion"; private static final int NYAACORE_ITEMSTACK_DEFAULT_DATAVERSION = 1139; private static NBTReadLimiter unlimitedNBTReadLimiter = null; private static int currentDataVersion; private static Cache<String, List<ItemStack>> itemDeserializerCache = CacheBuilder.newBuilder() .weigher((String k, List<ItemStack> v) -> k.getBytes().length) .maximumWeight(100L * 1024 * 1024).build(); // Hard Coded 100M static { currentDataVersion = Bukkit.getUnsafe().getDataVersion(); } /** * Get the binary representation of ItemStack * for fast ItemStack serialization * * @param itemStack the item to be serialized * @return binary NBT representation of the item stack */ public static byte[] itemToBinary(ItemStack itemStack) throws IOException { net.minecraft.server.v1_13_R2.ItemStack nativeItemStack = CraftItemStack.asNMSCopy(itemStack); NBTTagCompound nbtTagCompound = new NBTTagCompound(); nativeItemStack.save(nbtTagCompound); nbtTagCompound.setInt(NYAACORE_ITEMSTACK_DATAVERSION_KEY, currentDataVersion); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); nbtTagCompound.write(dos); byte[] outputByteArray = baos.toByteArray(); dos.close(); baos.close(); return outputByteArray; } /** * Get the ItemStack from its binary representation * for fast ItemStack deserialization * * @param nbt binary item nbt data * @return constructed item */ public static ItemStack itemFromBinary(byte[] nbt) throws ReflectiveOperationException, IOException { return itemFromBinary(nbt, 0, nbt.length); } public static ItemStack itemFromBinary(byte[] nbt, int offset, int len) throws ReflectiveOperationException, IOException { if (unlimitedNBTReadLimiter == null) { unlimitedNBTReadLimiter = NBTReadLimiter.a; } //Constructor<?> constructNativeItemStackFromNBTTagCompound = classNativeItemStack.getConstructor(classNBTTagCompound); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(nbt, offset, len); DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream); NBTTagCompound reconstructedNBTTagCompound = new NBTTagCompound(); reconstructedNBTTagCompound.load(dataInputStream, 0, unlimitedNBTReadLimiter); dataInputStream.close(); byteArrayInputStream.close(); int dataVersion = reconstructedNBTTagCompound.getInt(NYAACORE_ITEMSTACK_DATAVERSION_KEY); if (dataVersion > 0) { reconstructedNBTTagCompound.remove(NYAACORE_ITEMSTACK_DATAVERSION_KEY); } if (dataVersion < currentDataVersion) { // 1.12 to 1.13 if (dataVersion <= 0) { dataVersion = NYAACORE_ITEMSTACK_DEFAULT_DATAVERSION; } DSL.TypeReference dataConverterTypes_ITEM_STACK = DataConverterTypes.ITEM_STACK; DynamicOpsNBT DynamicOpsNBT_instance = DynamicOpsNBT.a; DataFixer dataFixer_instance = DataConverterRegistry.a(); Dynamic<NBTBase> dynamicInstance = new Dynamic<>(DynamicOpsNBT_instance, reconstructedNBTTagCompound); Dynamic<NBTBase> out = dataFixer_instance.update(dataConverterTypes_ITEM_STACK, dynamicInstance, dataVersion, currentDataVersion); reconstructedNBTTagCompound = (NBTTagCompound) out.getValue(); } net.minecraft.server.v1_13_R2.ItemStack reconstructedNativeItemStack = net.minecraft.server.v1_13_R2.ItemStack.a(reconstructedNBTTagCompound); return CraftItemStack.asBukkitCopy(reconstructedNativeItemStack); } private static byte[] compress(byte[] data) { byte[] ret; try (ByteArrayInputStream bis = new ByteArrayInputStream(data); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ByteStreams.copy(new DeflaterInputStream(bis), bos); ret = bos.toByteArray(); } catch (IOException ex) { throw new RuntimeException(ex); } return ret; } private static byte[] decompress(byte[] data) { byte[] ret; try (ByteArrayInputStream bis = new ByteArrayInputStream(data); ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ByteStreams.copy(new InflaterInputStream(bis), bos); ret = bos.toByteArray(); } catch (IOException ex) { throw new RuntimeException(ex); } return ret; } /* * * Structure of binary NBT list: * - First byte (n): number of items (currently limit to 0<=n<=127 i.e. MSB=0) * - Next 4*n bytes (s1~sn): size of binary nbt for each item * - Next sum(s1~sn) bytes: actual data nbt */ /** * Convert a list of items into compressed base64 string */ public static String itemsToBase64(List<ItemStack> items) { if (items.isEmpty()) return ""; if (items.size() > 127) { throw new IllegalArgumentException("Too many items"); } List<byte[]> nbts = new ArrayList<>(); for (ItemStack item : items) { try { nbts.add(itemToBinary(item)); } catch (Exception ex) { throw new RuntimeException(ex); } } byte[] uncompressed_binary; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeByte(items.size()); for (byte[] nbt : nbts) dos.writeInt(nbt.length); for (byte[] nbt : nbts) dos.write(nbt); uncompressed_binary = bos.toByteArray(); } catch (IOException ex) { throw new RuntimeException(ex); } return BaseEncoding.base64().encode(compress(uncompressed_binary)); } /** * Convert base64 string back to a list of items */ public static List<ItemStack> itemsFromBase64(String base64) { List<ItemStack> stack = itemDeserializerCache.getIfPresent(base64); if (stack != null) return stack.stream().map(ItemStack::clone).collect(Collectors.toList()); if (base64.length() <= 0) return new ArrayList<>(); byte[] uncompressedBinary = decompress(BaseEncoding.base64().decode(base64)); List<ItemStack> ret = new ArrayList<>(); try (ByteArrayInputStream bis = new ByteArrayInputStream(uncompressedBinary); DataInputStream dis = new DataInputStream(bis)) { int n = dis.readByte(); int[] nbtLength = new int[n]; for (int i = 0; i < n; i++) nbtLength[i] = dis.readInt(); for (int i = 0; i < n; i++) { byte[] tmp = new byte[nbtLength[i]]; dis.readFully(tmp); ret.add(itemFromBinary(tmp)); } } catch (IOException | ReflectiveOperationException ex) { throw new RuntimeException(ex); } itemDeserializerCache.put(base64, ret.stream().map(ItemStack::clone).collect(Collectors.toList())); return ret; } public static String itemToBase64(ItemStack item) { if (item == null) throw new IllegalArgumentException(); return itemsToBase64(Collections.singletonList(item)); } public static ItemStack itemFromBase64(String base64) { if (base64 == null) throw new IllegalArgumentException(); List<ItemStack> ret = itemsFromBase64(base64); if (ret != null && !ret.isEmpty()) return ret.get(0); return null; } public static String itemToJson(ItemStack itemStack) throws RuntimeException { NBTTagCompound nmsNbtTagCompoundObj; // This will just be an empty NBTTagCompound instance to invoke the saveNms method net.minecraft.server.v1_13_R2.ItemStack nmsItemStackObj; // This is the net.minecraft.server.ItemStack object received from the asNMSCopy method NBTTagCompound itemAsJsonObject; // This is the net.minecraft.server.ItemStack after being put through saveNmsItem method try { nmsNbtTagCompoundObj = new NBTTagCompound(); nmsItemStackObj = CraftItemStack.asNMSCopy(itemStack); itemAsJsonObject = nmsItemStackObj.save(nmsNbtTagCompoundObj); } catch (Throwable t) { throw new RuntimeException("failed to serialize itemstack to nms item", t); } // Return a string representation of the serialized object return itemAsJsonObject.toString(); } public static Object asNMSCopy(ItemStack itemStack) { return CraftItemStack.asNMSCopy(itemStack); } }
package com.InfinityRaider.AgriCraft; /* This is my first "real" mod, I've made this while learning to use Minecraft Forge to Mod Minecraft. The code might not be optimal but that wasn't the point of this project. Cheers to: - Pam for trusting me with her source code and support - Pahimar for making his code open source and for creating his Let's Mod Reboot Youtube series, I've learned a lot from this (also used some code, credits due where credits due) - VSWE for his "Forging a Minecraft Mod" summer courses - NealeGaming for his Minecraft modding tutorials on youtube I've annotated my code heavily, for myself and for possible others who might learn from it. Oh and keep on modding in the free world ~ InfinityRaider */ import com.InfinityRaider.AgriCraft.compatibility.ModIntegration; import com.InfinityRaider.AgriCraft.compatibility.minetweaker.CustomWood; import com.InfinityRaider.AgriCraft.compatibility.minetweaker.SeedBlacklist; import com.InfinityRaider.AgriCraft.compatibility.minetweaker.SeedMutation; import com.InfinityRaider.AgriCraft.farming.SoilWhitelist; import com.InfinityRaider.AgriCraft.handler.ConfigurationHandler; import com.InfinityRaider.AgriCraft.handler.GuiHandler; import com.InfinityRaider.AgriCraft.farming.mutation.MutationHandler; import com.InfinityRaider.AgriCraft.init.*; import com.InfinityRaider.AgriCraft.proxy.IProxy; import com.InfinityRaider.AgriCraft.reference.Names; import com.InfinityRaider.AgriCraft.reference.Reference; import com.InfinityRaider.AgriCraft.utility.LogHelper; import com.InfinityRaider.AgriCraft.utility.SeedHelper; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.network.NetworkRegistry; import minetweaker.MineTweakerAPI; @Mod(modid = Reference.MOD_ID,name = Reference.MOD_NAME,version = Reference.VERSION, guiFactory = Reference.GUI_FACTORY_CLASS) public class AgriCraft { @Mod.Instance(Reference.MOD_ID) public static AgriCraft instance; @SidedProxy(clientSide = Reference.CLIENT_PROXY_CLASS,serverSide = Reference.SERVER_PROXY_CLASS) public static IProxy proxy; @Mod.EventHandler public static void preInit(FMLPreInitializationEvent event) { LogHelper.info("Starting Pre-Initialization"); //find loaded mods ModIntegration.LoadedMods.init(); //register forge event handlers proxy.registerEventHandlers(); //setting up configuration file ConfigurationHandler.init(event); FMLCommonHandler.instance().bus().register(new ConfigurationHandler()); //initialize blocks Blocks.init(); //initialize crops Crops.init(); //initialize items Items.init(); LogHelper.info("Pre-Initialization Complete"); } @Mod.EventHandler public static void init(FMLInitializationEvent event) { LogHelper.info("Starting Initialization"); ResourceCrops.init(); Seeds.init(); NetworkRegistry.INSTANCE.registerGuiHandler(instance , new GuiHandler()); proxy.registerTileEntities(); proxy.registerRenderers(); ModIntegration.init(); if (Loader.isModLoaded(Names.Mods.minetweaker)) { MineTweakerAPI.registerClass(CustomWood.class); MineTweakerAPI.registerClass(SeedMutation.class); MineTweakerAPI.registerClass(SeedBlacklist.class); MineTweakerAPI.registerClass(SoilWhitelist.class); } LogHelper.info("Initialization Complete"); } @Mod.EventHandler public static void postInit(FMLPostInitializationEvent event) { LogHelper.info("Starting Post-Initialization"); Recipes.init(); CustomCrops.initCustomCrops(); SeedHelper.init(); MutationHandler.init(); SoilWhitelist.initSoils(); CustomCrops.initGrassSeeds(); if(!ConfigurationHandler.disableWorldGen) { WorldGen.init(); } proxy.initNEI(); proxy.initSeedInfo(); LogHelper.info("Post-Initialization Complete"); } }
package com.amee.platform.search; import com.amee.base.transaction.TransactionController; import com.amee.domain.IAMEEEntity; import com.amee.domain.ObjectType; import com.amee.domain.data.DataCategory; import com.amee.domain.data.DataItem; import com.amee.domain.data.ItemValue; import com.amee.platform.science.Amount; import com.amee.service.data.DataService; import com.amee.service.locale.LocaleService; import com.amee.service.metadata.MetadataService; import com.amee.service.tag.TagService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.NumericField; import org.apache.lucene.index.Term; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import java.util.ArrayList; import java.util.List; @Configurable(autowire = Autowire.BY_TYPE) public class SearchIndexer implements Runnable { public static class DocumentContext { // Current Data Category. public String dataCategoryUid; // Should All Data Categories be updated regardless of modification date? public boolean handleDataCategories = false; // Should Data Item documents be handled when handling a Data Category. public boolean handleDataItems = false; // Work-in-progress List of Data Item Documents. public List<Document> dataItemDocs; // Current Data Item. public DataItem dataItem; // Current Data Item Document public Document dataItemDoc; } private final Log log = LogFactory.getLog(getClass()); private final Log searchLog = LogFactory.getLog("search"); public final static DateTimeFormatter DATE_TO_SECOND = DateTimeFormat.forPattern("yyyyMMddHHmmss"); @Autowired private TransactionController transactionController; @Autowired private DataService dataService; @Autowired private MetadataService metadataService; @Autowired private LocaleService localeService; @Autowired private TagService tagService; @Autowired private SearchQueryService searchQueryService; @Autowired private LuceneService luceneService; private DocumentContext ctx; private DataCategory dataCategory; private boolean newCategory = false; private SearchIndexer() { super(); } public SearchIndexer(DocumentContext ctx) { super(); this.ctx = ctx; } @Override public void run() { try { searchLog.info(ctx.dataCategoryUid + "|Started processing DataCategory."); // Start persistence session. transactionController.beforeHandle(false); // Get the DataCategory and handle. dataCategory = dataService.getDataCategoryByUid(ctx.dataCategoryUid, null); if (dataCategory != null) { updateDataCategory(); } else { searchLog.warn(ctx.dataCategoryUid + "|DataCategory not found."); } } catch (Throwable t) { transactionController.setRollbackOnly(); searchLog.error(ctx.dataCategoryUid + "|Error processing DataCategory."); log.error("run() Caught Throwable: " + t.getMessage(), t); } finally { transactionController.end(); searchLog.info(ctx.dataCategoryUid + "|Completed processing DataCategory."); } } /** * Update or remove Data Category & Data Items from the search index. */ public void updateDataCategory() { if (!dataCategory.isTrash()) { Document document = searchQueryService.getDocument(dataCategory); if (document != null) { Field modifiedField = document.getField("entityModified"); if (modifiedField != null) { DateTime modifiedInIndex = DATE_TO_SECOND.parseDateTime(modifiedField.stringValue()); DateTime modifiedInDatabase = new DateTime(dataCategory.getModified()).withMillisOfSecond(0); if (ctx.handleDataCategories || ctx.handleDataItems || modifiedInDatabase.isAfter(modifiedInIndex)) { searchLog.info(ctx.dataCategoryUid + "|DataCategory has been modified or re-index requested, updating."); handleDataCategory(); } else { searchLog.info(ctx.dataCategoryUid + "|DataCategory is up-to-date, skipping."); } } else { searchLog.info(ctx.dataCategoryUid + "|The DataCategory modified field was missing, updating"); handleDataCategory(); } } else { searchLog.info(ctx.dataCategoryUid + "|DataCategory not in index, adding for the first time."); newCategory = true; ctx.handleDataItems = true; handleDataCategory(); } } else { searchLog.info(ctx.dataCategoryUid + "|DataCategory needs to be removed."); searchQueryService.removeDataCategory(dataCategory); searchQueryService.removeDataItems(dataCategory); } } /** * Add a Document for the supplied DataCategory to the Lucene index. */ protected void handleDataCategory() { log.debug("handleDataCategory() " + dataCategory.toString()); // Get Data Category Document. Document dataCategoryDoc = getDocumentForDataCategory(dataCategory); // Handle Data Items (Create, store & update documents). if (ctx.handleDataItems) { handleDataItems(); } // Are handling a new Data Category? if (!newCategory) { // Store / update the Data Category Document. luceneService.updateDocument( dataCategoryDoc, new Term("entityType", ObjectType.DC.getName()), new Term("entityUid", dataCategory.toString())); } else { // Add the new Document. luceneService.addDocument(dataCategoryDoc); } } /** * Create all DataItem documents for the supplied DataCategory. */ protected void handleDataItems() { ctx.dataItemDoc = null; ctx.dataItemDocs = null; // There are only Data Items for a Data Category if there is an Item Definition. if (dataCategory.getItemDefinition() != null) { log.info("handleDataItems() Starting... (" + dataCategory.toString() + ")"); // Pre-cache metadata and locales for the Data Items. metadataService.loadMetadatasForItemValueDefinitions(dataCategory.getItemDefinition().getItemValueDefinitions()); localeService.loadLocaleNamesForItemValueDefinitions(dataCategory.getItemDefinition().getItemValueDefinitions()); List<DataItem> dataItems = dataService.getDataItems(dataCategory, false); metadataService.loadMetadatasForDataItems(dataItems); localeService.loadLocaleNamesForDataItems(dataItems); // Iterate over all Data Items and create Documents. ctx.dataItemDocs = new ArrayList<Document>(); for (DataItem dataItem : dataItems) { ctx.dataItem = dataItem; // Create new Data Item Document. ctx.dataItemDoc = getDocumentForDataItem(dataItem); ctx.dataItemDocs.add(ctx.dataItemDoc); // Handle the Data Item Values. handleDataItemValues(ctx); } // Clear caches. metadataService.clearMetadatas(); localeService.clearLocaleNames(); // Ensure we clear existing DataItem Documents for this Data Category (only if the category is not new). if (!newCategory) { searchQueryService.removeDataItems(dataCategory); } // Add the new Data Item Documents to the index (if any). luceneService.addDocuments(ctx.dataItemDocs); log.info("handleDataItems() ...done (" + dataCategory.toString() + ")."); } else { log.debug("handleDataItems() DataCategory does not have items: " + dataCategory.toString()); // Ensure we clear any Data Item Documents for this Data Category. searchQueryService.removeDataItems(dataCategory); } } // Lucene Document creation. protected Document getDocumentForDataCategory(DataCategory dataCategory) { Document doc = getDocumentForAMEEEntity(dataCategory); doc.add(new Field("name", dataCategory.getName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("path", dataCategory.getPath().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.add(new Field("fullPath", dataCategory.getFullPath().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.add(new Field("wikiName", dataCategory.getWikiName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("wikiDoc", dataCategory.getWikiDoc().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("provenance", dataCategory.getProvenance().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("authority", dataCategory.getAuthority().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); if (dataCategory.getDataCategory() != null) { doc.add(new Field("parentUid", dataCategory.getDataCategory().getUid(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("parentWikiName", dataCategory.getDataCategory().getWikiName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } if (dataCategory.getItemDefinition() != null) { doc.add(new Field("itemDefinitionUid", dataCategory.getItemDefinition().getUid(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("itemDefinitionName", dataCategory.getItemDefinition().getName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } doc.add(new Field("tags", tagService.getTagsCSV(dataCategory).toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); return doc; } protected Document getDocumentForDataItem(DataItem dataItem) { Document doc = getDocumentForAMEEEntity(dataItem); doc.add(new Field("name", dataItem.getName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("path", dataItem.getPath().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.add(new Field("fullPath", dataItem.getFullPath().toLowerCase() + "/" + dataItem.getDisplayPath().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); doc.add(new Field("wikiDoc", dataItem.getWikiDoc().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("provenance", dataItem.getProvenance().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("categoryUid", dataItem.getDataCategory().getUid(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("categoryWikiName", dataItem.getDataCategory().getWikiName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); doc.add(new Field("itemDefinitionUid", dataItem.getItemDefinition().getUid(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("itemDefinitionName", dataItem.getItemDefinition().getName().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); for (ItemValue itemValue : dataItem.getItemValues()) { if (itemValue.isUsableValue()) { if (itemValue.getItemValueDefinition().isDrillDown()) { doc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); } else { if (itemValue.isDouble()) { try { doc.add(new NumericField(itemValue.getDisplayPath()).setDoubleValue(new Amount(itemValue.getValue()).getValue())); } catch (NumberFormatException e) { log.warn("getDocumentForDataItem() Could not parse '" + itemValue.getDisplayPath() + "' value '" + itemValue.getValue() + "' for DataItem " + dataItem.toString() + "."); doc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } } else { doc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } } } } doc.add(new Field("label", dataItem.getLabel().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); return doc; } protected Document getDocumentForAMEEEntity(IAMEEEntity entity) { Document doc = new Document(); doc.add(new Field("entityType", entity.getObjectType().getName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("entityId", entity.getId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("entityUid", entity.getUid(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("entityCreated", new DateTime(entity.getCreated()).toString(DATE_TO_SECOND), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("entityModified", new DateTime(entity.getModified()).toString(DATE_TO_SECOND), Field.Store.YES, Field.Index.NOT_ANALYZED)); return doc; } protected void handleDataItemValues(DocumentContext ctx) { for (ItemValue itemValue : ctx.dataItem.getItemValues()) { if (itemValue.isUsableValue()) { if (itemValue.getItemValueDefinition().isDrillDown()) { ctx.dataItemDoc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.NOT_ANALYZED)); } else { if (itemValue.isDouble()) { try { ctx.dataItemDoc.add(new NumericField(itemValue.getDisplayPath()).setDoubleValue(new Amount(itemValue.getValue()).getValue())); } catch (NumberFormatException e) { log.warn("handleDataItemValues() Could not parse '" + itemValue.getDisplayPath() + "' value '" + itemValue.getValue() + "' for DataItem " + ctx.dataItem.toString() + "."); ctx.dataItemDoc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } } else { ctx.dataItemDoc.add(new Field(itemValue.getDisplayPath(), itemValue.getValue().toLowerCase(), Field.Store.NO, Field.Index.ANALYZED)); } } } } } }
package com.carpentersblocks.tileentity; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.UUID; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import com.carpentersblocks.block.BlockCoverable; import com.carpentersblocks.util.BlockProperties; import com.carpentersblocks.util.handler.DesignHandler; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedUtil; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; public class TEBase extends TileEntity implements IProtected { private static final String TAG_ATTR = "cbAttribute"; private static final String TAG_ATTR_LIST = "cbAttrList"; private static final String TAG_METADATA = "cbMetadata"; private static final String TAG_OWNER = "cbOwner"; private static final String TAG_CHISEL_DESIGN = "cbChiselDesign"; private static final String TAG_DESIGN = "cbDesign"; public static final byte[] ATTR_COVER = { 0, 1, 2, 3, 4, 5, 6 }; public static final byte[] ATTR_DYE = { 7, 8, 9, 10, 11, 12, 13 }; public static final byte[] ATTR_OVERLAY = { 14, 15, 16, 17, 18, 19, 20 }; public static final byte ATTR_ILLUMINATOR = 21; public static final byte ATTR_PLANT = 22; public static final byte ATTR_SOIL = 23; public static final byte ATTR_FERTILIZER = 24; public static final byte ATTR_UPGRADE = 25; /** Map holding all block attributes. */ protected Map<Byte, ItemStack> cbAttrMap = new HashMap<Byte, ItemStack>(); /** Chisel design for each side and base block. */ protected String[] cbChiselDesign = { "", "", "", "", "", "", "" }; /** Holds specific block information like facing, states, etc. */ protected short cbMetadata; /** Design name. */ protected String cbDesign = ""; /** Owner of tile entity. */ protected String cbOwner = ""; @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); cbAttrMap.clear(); if (nbt.hasKey("owner")) { MigrationHelper.updateMappingsOnRead(this, nbt); } else { NBTTagList nbttaglist = nbt.getTagList(TAG_ATTR_LIST, 10); for (int idx = 0; idx < nbttaglist.tagCount(); ++idx) { NBTTagCompound nbt1 = nbttaglist.getCompoundTagAt(idx); ItemStack tempStack = ItemStack.loadItemStackFromNBT(nbt1); tempStack.stackSize = 1; // All ItemStacks pre-3.2.7 DEV R3 stored original stack sizes, reduce them here. byte attrId = (byte) (nbt1.getByte(TAG_ATTR) & 255); cbAttrMap.put(attrId, tempStack); } for (int idx = 0; idx < 7; ++idx) { cbChiselDesign[idx] = nbt.getString(TAG_CHISEL_DESIGN + "_" + idx); } cbMetadata = nbt.getShort(TAG_METADATA); cbDesign = nbt.getString(TAG_DESIGN); cbOwner = nbt.getString(TAG_OWNER); } /* * Attempt to update owner name to new UUID format. * TODO: Remove when player name-changing system is switched on */ if (FMLCommonHandler.instance().getSide().equals(Side.SERVER)) { ProtectedUtil.updateOwnerUUID(this); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); NBTTagList itemstack_list = new NBTTagList(); Iterator iterator = cbAttrMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); NBTTagCompound nbt1 = new NBTTagCompound(); nbt1.setByte(TAG_ATTR, (Byte) entry.getKey()); ((ItemStack)entry.getValue()).writeToNBT(nbt1); itemstack_list.appendTag(nbt1); } nbt.setTag(TAG_ATTR_LIST, itemstack_list); for (int idx = 0; idx < 7; ++idx) { nbt.setString(TAG_CHISEL_DESIGN + "_" + idx, cbChiselDesign[idx]); } nbt.setShort(TAG_METADATA, cbMetadata); nbt.setString(TAG_DESIGN, cbDesign); nbt.setString(TAG_OWNER, cbOwner); } @Override /** * Overridden in a sign to provide the text. */ public Packet getDescriptionPacket() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, nbt); } @Override /** * Called when you receive a TileEntityData packet for the location this * TileEntity is currently in. On the client, the NetworkManager will always * be the remote server. On the server, it will be whomever is responsible for * sending the packet. * * @param net The NetworkManager the packet originated from * @param pkt The data packet */ public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { readFromNBT(pkt.func_148857_g()); markDirty(); if (worldObj.isRemote) { worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); // TODO: Rename to updateAllLightByTypes worldObj.func_147451_t(xCoord, yCoord, zCoord); } } /** * Called from Chunk.setBlockIDWithMetadata, determines if this tile entity should be re-created when the ID, or Metadata changes. * Use with caution as this will leave straggler TileEntities, or create conflicts with other TileEntities if not used properly. * * @param oldID The old ID of the block * @param newID The new ID of the block (May be the same) * @param oldMeta The old metadata of the block * @param newMeta The new metadata of the block (May be the same) * @param world Current world * @param x X Position * @param y Y Position * @param z Z Position * @return True to remove the old tile entity, false to keep it in tact {and create a new one if the new values specify to} */ @Override public boolean shouldRefresh(Block oldBlock, Block newBlock, int oldMeta, int newMeta, World world, int x, int y, int z) { /* * This is a curious method. * * Essentially, when doing most block logic server-side, changes * to blocks will momentarily "flash" to their default state * when rendering client-side. This is most noticeable when adding * or removing covers for the first time. * * Making the tile entity refresh only when the block is first created * is not only reasonable, but fixes this behavior. */ return oldBlock != newBlock; } @Override public void markDirty() { // Update light value cache ((BlockCoverable)getBlockType()).updateLightValue(getWorldObj(), xCoord, yCoord, zCoord); super.markDirty(); } @Override /** * Called when the chunk this TileEntity is on is Unloaded. */ public void onChunkUnload() { int hash = BlockCoverable.hashCoords(xCoord, yCoord, zCoord); BlockCoverable.cache.remove(hash); } /** * Sets owner of tile entity. */ @Override public void setOwner(UUID uuid) { cbOwner = uuid.toString(); markDirty(); } @Override public String getOwner() { return cbOwner; } @Override /** * Determines if this TileEntity requires update calls. * @return True if you want updateEntity() to be called, false if not */ public boolean canUpdate() { return false; } public boolean hasAttribute(byte attrId) { return cbAttrMap.containsKey(attrId); } public ItemStack getAttribute(byte attrId) { return cbAttrMap.get(attrId); } public ItemStack getAttributeForDrop(byte attrId) { ItemStack itemStack = cbAttrMap.get(attrId); // If cover, check for rotation and restore default metadata if (attrId <= ATTR_COVER[6]) { setDefaultMetadata(itemStack); } return itemStack; } /** * Will restore cover to default state before returning {@link ItemStack}. * <p> * Corrects log rotation, among other things. * * @param rand a {@link Random} reference * @param itemStack the {@link ItemStack} * @return the cover {@link ItemStack} in it's default state */ private ItemStack setDefaultMetadata(ItemStack itemStack) { Block block = BlockProperties.toBlock(itemStack); // Correct rotation metadata before dropping block if (BlockProperties.blockRotates(itemStack) || block instanceof BlockDirectional) { int dmgDrop = block.damageDropped(itemStack.getItemDamage()); Item itemDrop = block.getItemDropped(itemStack.getItemDamage(), getWorldObj().rand, /* Fortune */ 0); /* Check if block drops itself, and, if so, correct the damage value to the block's default. */ if (itemDrop != null && itemDrop.equals(itemStack.getItem()) && dmgDrop != itemStack.getItemDamage()) { itemStack.setItemDamage(dmgDrop); } } return itemStack; } public void addAttribute(byte attrId, ItemStack itemStack) { if (!hasAttribute(attrId) && itemStack != null) { ItemStack reducedStack = null; if (itemStack != null) { reducedStack = ItemStack.copyItemStack(itemStack); reducedStack.stackSize = 1; } cbAttrMap.put(attrId, reducedStack); World world = getWorldObj(); if (world != null) { Block block = itemStack == null ? getBlockType() : BlockProperties.toBlock(itemStack); if (attrId < 7) { int metadata = itemStack == null ? 0 : itemStack.getItemDamage(); if (attrId == ATTR_COVER[6]) { world.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 0); } world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block); } else if (attrId == ATTR_PLANT | attrId == ATTR_SOIL) { world.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, block); } if (attrId == ATTR_FERTILIZER) { /* Play sound when fertilizing plants.. though I've never heard it before. */ getWorldObj().playAuxSFX(2005, xCoord, yCoord, zCoord, 0); } world.markBlockForUpdate(xCoord, yCoord, zCoord); } markDirty(); } } /** * Will remove the attribute from map once block drop is complete. * <p> * Should only be called externally by {@link BlockCoverable#onBlockEventReceived}. * * @param attrId */ public void onAttrDropped(byte attrId) { cbAttrMap.remove(attrId); getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord); markDirty(); } /** * Initiates block drop event, which will remove attribute from tile entity. * * @param attrId the attribute ID */ public void createBlockDropEvent(byte attrId) { getWorldObj().addBlockEvent(xCoord, yCoord, zCoord, getBlockType(), BlockCoverable.EVENT_ID_DROP_ATTR, attrId); } public void removeAttributes(int side) { createBlockDropEvent(ATTR_COVER[side]); createBlockDropEvent(ATTR_DYE[side]); createBlockDropEvent(ATTR_OVERLAY[side]); if (side == 6) { createBlockDropEvent(ATTR_ILLUMINATOR); } } /** * Returns whether block has pattern. */ public boolean hasChiselDesign(int side) { return DesignHandler.listChisel.contains(getChiselDesign(side)); } /** * Returns pattern. */ public String getChiselDesign(int side) { return cbChiselDesign[side]; } /** * Sets pattern. */ public boolean setChiselDesign(int side, String iconName) { if (!cbChiselDesign.equals(iconName)) { cbChiselDesign[side] = iconName; getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord); return true; } return false; } public void removeChiselDesign(int side) { if (!cbChiselDesign.equals("")) { cbChiselDesign[side] = ""; getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord); } } /** * Gets block-specific data. * * @return the data */ public int getData() { return cbMetadata & 0xffff; } /** * Sets block-specific data. */ public boolean setData(int data) { if (data != getData()) { cbMetadata = (short) data; getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord); return true; } return false; } public boolean hasDesign() { return DesignHandler.getListForType(getBlockDesignType()).contains(cbDesign); } public String getDesign() { return cbDesign; } public boolean setDesign(String name) { if (!cbDesign.equals(name)) { cbDesign = name; getWorldObj().markBlockForUpdate(xCoord, yCoord, zCoord); return true; } return false; } public boolean removeDesign() { return setDesign(""); } public String getBlockDesignType() { String name = getBlockType().getUnlocalizedName(); return name.substring(new String("tile.blockCarpenters").length()).toLowerCase(); } public boolean setNextDesign() { return setDesign(DesignHandler.getNext(getBlockDesignType(), cbDesign)); } public boolean setPrevDesign() { return setDesign(DesignHandler.getPrev(getBlockDesignType(), cbDesign)); } /** * Sets block metadata without causing a render update. * <p> * As part of mimicking a cover block, the metadata must be changed * to better represent the cover properties. * <p> * This is normally followed up by calling {@link setMetadataFromCover}. */ public void setMetadata(int metadata) { getWorldObj().setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 4); } /** * Restores default metadata for block from base cover. */ public void restoreMetadata() { int metadata = hasAttribute(ATTR_COVER[6]) ? getAttribute(ATTR_COVER[6]).getItemDamage() : 0; getWorldObj().setBlockMetadataWithNotify(xCoord, yCoord, zCoord, metadata, 4); } }
package com.conveyal.r5.profile; import com.conveyal.r5.analyst.scenario.Scenario; import java.time.*; import com.conveyal.r5.api.util.LegMode; import com.conveyal.r5.api.util.SearchType; import com.conveyal.r5.api.util.TransitModes; import com.conveyal.r5.model.json_serialization.*; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import graphql.schema.DataFetchingEnvironment; import java.io.Serializable; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.EnumSet; /** * All the modifiable parameters for profile routing. */ public class ProfileRequest implements Serializable, Cloneable { // Analyst used to serialize the request along with regional analysis results into MapDB. // In Analysis, the request is still saved but as JSON in MongoDB. private static final long serialVersionUID = -6501962907644662303L; //From and to zonedDateTime filled in GraphQL request //Based on those two variables and timezone from/totime and date is filled //Since from/to time and date is assumed to be in local timezone AKA same timezone as TransportNetwork private ZonedDateTime fromZonedDateTime; private ZonedDateTime toZonedDateTime; /** The latitude of the origin. */ public double fromLat; /** The longitude of the origin. */ public double fromLon; /** The latitude of the destination. Must be set even in Analyst mode. */ public double toLat; /** The longitude of the destination. Must be set even in Analyst mode. */ public double toLon; /** The beginning of the departure window, in seconds since midnight. */ public int fromTime; /** The end of the departure window, in seconds since midnight. */ public int toTime; /** The speed of walking, in meters per second */ public float walkSpeed = 1.3f; /** The speed of cycling, in meters per second */ public float bikeSpeed = 4f; /** maximum level of traffic stress for cycling, 1 - 4 */ public int bikeTrafficStress = 4; /** The speed of driving, in meters per second. Roads from OSM use the speed limit, this is the speed used when propagating from the street network to a pointset. */ public float carSpeed = 2.22f; // ~8 km/h /** Maximum time to reach the destination without using transit in minutes */ public int streetTime = 60; /** * Maximum walk time before and after using transit, in minutes * * NB the time to reach the destination after leaving transit is considered separately from the time to reach * transit at the start of the search; e.g. if you set maxWalkTime to 600 (ten minutes), you could potentially walk * up to ten minutes to reach transit, and up to _another_ ten minutes to reach the destination after leaving transit. * * This is required because hard resource limiting on non-objective variables is algorithmically invalid. Consider * a case where there is a destination 10 minutes from transit and an origin 5 minutes walk from a feeder bus and * 15 minutes walk from a fast train, and the walk budget is 20 minutes. If an intermediate point in the search * (for example, a transfer station) is reached by the fast train before it is reached by the bus, the route using * the bus will be dominated. When we leave transit, though, we have already used up 15 minutes of our walk budget * and don't have enough remaining to reach the destination. * * This is solved by using separate walk budgets at the origin and destination. It could also be solved (although this * would slow the algorithm down) by retaining all Pareto-optimal combinations of (travel time, walk distance). */ public int maxWalkTime = 30; /** Maximum bike time when using transit, in minutes */ public int maxBikeTime = 30; /** Maximum car time before when using transit, in minutes */ public int maxCarTime = 30; /** Minimum time to ride a bike (to prevent extremely short bike legs), in minutes */ public int minBikeTime = 5; /** Minimum time to drive (to prevent extremely short driving legs), in minutes */ public int minCarTime = 5; /** The date of the search */ public LocalDate date; /** the maximum number of options presented PER ACCESS MODE */ public int limit; /** The modes used to access transit */ @JsonSerialize(using = LegModeSetSerializer.class) @JsonDeserialize(using = LegModeSetDeserializer.class) public EnumSet<LegMode> accessModes; /** The modes used to reach the destination after leaving transit */ @JsonSerialize(using = LegModeSetSerializer.class) @JsonDeserialize(using = LegModeSetDeserializer.class) public EnumSet<LegMode> egressModes; /** The modes used to reach the destination without transit */ @JsonSerialize(using = LegModeSetSerializer.class) @JsonDeserialize(using = LegModeSetDeserializer.class) public EnumSet<LegMode> directModes; /** The transit modes used */ @JsonSerialize(using = TransitModeSetSerializer.class) @JsonDeserialize(using = TransitModeSetDeserializer.class) public EnumSet<TransitModes> transitModes; /** * This parameter compensates for the fact that GTFS does not contain information about schedule deviation (lateness). * The min-max travel time range for some trains is zero, since the trips are reported to always have the same * timings in the schedule. Such an option does not overlap (temporally) its alternatives, and is too easily * eliminated by an alternative that is only marginally better. We want to effectively push the max travel time of * alternatives out a bit to account for the fact that they don't always run on schedule. */ public int suboptimalMinutes = 5; /** * The maximum duration of any transit trip found by this search. Results used to be very sensitive to this * when we were using mean travel times, now we use medians so we could set this to 2 hours. */ public int maxTripDurationMinutes = 4 * 60; /** * The maximum number of rides, e.g. taking the L2 to the Red line to the Green line would be three rides. */ public int maxRides = 8; /** A non-destructive scenario to apply when executing this request */ public Scenario scenario; /** * The ID of a scenario stored in S3 as JSON. * You must specify one (but only one) of scenario or scenarioId. * It is an error if both scenario and the scenarioId are specified. */ public String scenarioId; @JsonSerialize(using=ZoneIdSerializer.class) @JsonDeserialize(using=ZoneIdDeserializer.class) public ZoneId zoneId = ZoneOffset.UTC; /** * Require all streets and transit to be wheelchair-accessible. This is not fully implemented and doesn't work * at all in Analysis (FastRaptorWorker), only in Modeify (McRaptorSuboptimalPathProfileRouter). */ public boolean wheelchair; /** Whether this is a depart-after or arrive-by search */ private SearchType searchType; /** * If true current search is reverse search AKA we are looking for a path from destination to origin in reverse * It differs from searchType because it is used as egress search */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) public boolean reverseSearch = false; /** * Maximum fare for constraining monetary cost of paths during search in Analysis. * If nonnegative, fares will be used in routing. */ public int maxFare = -1; /** * Number of Monte Carlo draws to take for frequency searches. * * We loop over all departure minutes and do a search on the scheduled portion of the network, and then while * holding the departure minute and scheduled search results stable, we run several Monte Carlo searches with * randomized frequency schedules that minute. The number of Monte Carlo draws does not need to be particularly * high as it happens each minute, and there is likely a lot of repetition in the scheduled service * (i.e. many minutes look like each other), so several minutes' Monte Carlo draws are effectively pooled. * * The algorithm divides up the number of draws into an equal number at each minute of the time window, then rounds up. * Note that the algorithm may actually take somewhat more draws than this, depending on the width of your time window. * As an extreme example, if your time window is 120 minutes and you request 121 draws, you will actually get 240, because * 1 &lt; 121 / 120 &lt; 2. */ public int monteCarloDraws = 220; public ProfileRequest clone () { try { return (ProfileRequest) super.clone(); } catch (CloneNotSupportedException e) { // checked clonenotsupportedexception is about the stupidest thing in java throw new RuntimeException(e); } } /** * Returns number of milliseconds UNIX time made with date and fromTime * It reads date as date in transportNetwork timezone when it is converted to UNIX time it is in UTC * It needs to be decided how to do this correctly: #37 * If date isn't set current date is used. Time is empty (one hour before midnight in UTC if +1 timezone is used) * uses {@link #getFromTimeDateZD()} */ @JsonIgnore public long getFromTimeDate() { return getFromTimeDateZD().toInstant().toEpochMilli(); } /** * Returns ZonedDateTime made with date and fromTime fields * It reads date as date in transportNetwork timezone when it is converted to UNIX time it is in UTC * It needs to be decided how to do this correctly: #37 * If date isn't set current date is used. Time is empty (one hour before midnight in UTC if +1 timezone is used) */ @JsonIgnore public ZonedDateTime getFromTimeDateZD() { ZonedDateTime currentDateTime; if (date == null) { currentDateTime = ZonedDateTime.now(zoneId).truncatedTo(ChronoUnit.DAYS); } else { currentDateTime = ZonedDateTime.of(date.getYear(), date.getMonthValue(), date.getDayOfMonth(), 0,0,0,0,zoneId); } //fromTime is in seconds and there are 1000 ms in a second return currentDateTime.plusSeconds(fromTime); } /** * @return the speed at which the given mode will traverse street edges, in floating point meters per second. */ @JsonIgnore public float getSpeedForMode (StreetMode streetMode) { switch (streetMode) { case WALK: return walkSpeed; case BICYCLE: return bikeSpeed; case CAR: return carSpeed; default: break; } throw new IllegalArgumentException("getSpeedForMode(): Invalid mode " + streetMode); } /** * @return the maximum pre-transit travel time for the given mode in minutes */ @JsonIgnore public int getMaxAccessTimeForMode (StreetMode mode) { switch (mode) { case CAR: return maxCarTime; case BICYCLE: return maxBikeTime; case WALK: return maxWalkTime; default: throw new IllegalArgumentException("Invalid mode"); } } /** * @return true if there is any transitMode in transitModes (Safe to call if transitModes is null) */ public boolean hasTransit() { return this.transitModes != null && !this.transitModes.isEmpty(); } /** * Factory method to create a profile request with query parameters from a GraphQL request */ public static ProfileRequest fromGraphqlEnvironment(DataFetchingEnvironment environment, ZoneId timezone) { ProfileRequest profileRequest = new ProfileRequest(); profileRequest.zoneId = timezone; String operation = environment.getFields().get(0).getName(); //ZonedDatetime is used to fill fromTime/toTime and date //we need to have a network Timezone for that so that all the times are in network own timezone profileRequest.fromZonedDateTime = environment.getArgument("fromTime"); profileRequest.toZonedDateTime = environment.getArgument("toTime"); profileRequest.setTime(); profileRequest.wheelchair = environment.getArgument("wheelchair"); if (operation.equals("plan")) { profileRequest.searchType = environment.getArgument("searchType"); } //FIXME: if any of those three values is integer not float it gets converted to java integer instead of Double (So why did we even specify type)? // this is needed since walkSpeed/bikeSpeed/carSpeed are GraphQLFloats which are converted to java Doubles double walkSpeed = environment.getArgument("walkSpeed"); profileRequest.walkSpeed = (float) walkSpeed; double bikeSpeed = environment.getArgument("bikeSpeed"); profileRequest.bikeSpeed = (float) bikeSpeed; double carSpeed = environment.getArgument("carSpeed"); profileRequest.carSpeed = (float) carSpeed; profileRequest.streetTime = environment.getArgument("streetTime"); profileRequest.maxWalkTime = environment.getArgument("maxWalkTime"); profileRequest.maxBikeTime = environment.getArgument("maxBikeTime"); profileRequest.maxCarTime = environment.getArgument("maxCarTime"); profileRequest.minBikeTime = environment.getArgument("minBikeTime"); profileRequest.minCarTime = environment.getArgument("minCarTime"); profileRequest.limit = environment.getArgument("limit"); profileRequest.suboptimalMinutes = environment.getArgument("suboptimalMinutes"); profileRequest.bikeTrafficStress = environment.getArgument("bikeTrafficStress"); //Bike traffic stress needs to be between 1 and 4 if (profileRequest.bikeTrafficStress > 4) { profileRequest.bikeTrafficStress = 4; } else if (profileRequest.bikeTrafficStress < 1) { profileRequest.bikeTrafficStress = 1; } //This is always set otherwise GraphQL validation fails profileRequest.fromLat = environment.getArgument("fromLat"); profileRequest.fromLon = environment.getArgument("fromLon"); profileRequest.toLat = environment.getArgument("toLat"); profileRequest.toLon = environment.getArgument("toLon"); //Transit modes can be empty if searching for path without transit is requested Collection<TransitModes> transitModes = environment.getArgument("transitModes"); if (!transitModes.isEmpty()) { //If there is TRANSIT mode in transit modes all of transit modes need to be added. if (transitModes.contains(TransitModes.TRANSIT)) { profileRequest.transitModes = EnumSet.allOf(TransitModes.class); } else { //Otherwise only requested modes are copied profileRequest.transitModes = EnumSet.copyOf(transitModes); } } profileRequest.accessModes = EnumSet.copyOf((Collection<LegMode>) environment.getArgument("accessModes")); profileRequest.egressModes = EnumSet.copyOf((Collection<LegMode>)environment.getArgument("egressModes")); Collection<LegMode> directModes = environment.getArgument("directModes"); //directModes can be empty if we only want transit searches if (!directModes.isEmpty()) { profileRequest.directModes = EnumSet.copyOf(directModes); } else { profileRequest.directModes = EnumSet.noneOf(LegMode.class); } return profileRequest; } /** * Converts from/to zonedDateTime to graph timezone and fill from/totime and date */ private void setTime() { if (fromZonedDateTime != null) { fromZonedDateTime = fromZonedDateTime.withZoneSameInstant(zoneId); fromTime = fromZonedDateTime.getHour()*3600+fromZonedDateTime.getMinute()*60+fromZonedDateTime.getSecond(); date = fromZonedDateTime.toLocalDate(); } if (toZonedDateTime != null) { toZonedDateTime = toZonedDateTime.withZoneSameInstant(zoneId); toTime = toZonedDateTime.getHour() * 3600 + toZonedDateTime.getMinute() * 60 + toZonedDateTime.getSecond(); date = toZonedDateTime.toLocalDate(); } } /** * Sets time and date from fromTime and toTime * * It is used in tests * * @param fromTime The beginning of the departure window, in ISO 8061 YYYY-MM-DDTHH:MM:SS+HH:MM * @param toTime The end of the departure window, in ISO 8061 YYYY-MM-DDTHH:MM:SS+HH:MM */ public void setTime(String fromTime, String toTime) { fromZonedDateTime = ZonedDateTime.parse(fromTime); toZonedDateTime = ZonedDateTime.parse(toTime); setTime(); } /** * Returns maxCar/Bike/Walk based on LegMode * * @param mode * @return */ @JsonIgnore public int getTimeLimit(LegMode mode) { switch (mode) { case CAR: return maxCarTime * 60; case BICYCLE: return maxBikeTime * 60; case WALK: return maxWalkTime * 60; default: System.err.println("Unknown mode in getTimeLimit:"+mode.toString()); return streetTime * 60; } } /** * Returns minCar/BikeTime based on StreetMode * * default is 0 * * @param mode * @return min number of seconds that this mode should be used to get to stop/Park ride/bike share etc. */ @JsonIgnore public int getMinTimeLimit(StreetMode mode) { switch (mode) { case CAR: return minCarTime * 60; case BICYCLE: return minBikeTime * 60; default: return 0; } } /** Return the length of the time window in minutes */ @JsonIgnore public int getTimeWindowLengthMinutes() { return (toTime - fromTime) / 60; } /** * Return the number of Monte Carlo draws that must be done each minute to get at least the desired number of total * Monte Carlo draws over all minutes. */ @JsonIgnore public int getMonteCarloDrawsPerMinute() { return (int) Math.ceil((double) monteCarloDraws / getTimeWindowLengthMinutes()); } }
package com.fasterxml.jackson.core; import java.io.*; import java.lang.ref.SoftReference; import java.net.URL; import com.fasterxml.jackson.core.format.InputAccessor; import com.fasterxml.jackson.core.format.MatchStrength; import com.fasterxml.jackson.core.io.*; import com.fasterxml.jackson.core.json.*; import com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer; import com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer; import com.fasterxml.jackson.core.util.BufferRecycler; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; /** * The main factory class of Jackson package, used to configure and * construct reader (aka parser, {@link JsonParser}) * and writer (aka generator, {@link JsonGenerator}) * instances. *<p> * Factory instances are thread-safe and reusable after configuration * (if any). Typically applications and services use only a single * globally shared factory instance, unless they need differently * configured factories. Factory reuse is important if efficiency matters; * most recycling of expensive construct is done on per-factory basis. *<p> * Creation of a factory instance is a light-weight operation, * and since there is no need for pluggable alternative implementations * (as there is no "standard" JSON processor API to implement), * the default constructor is used for constructing factory * instances. * * @author Tatu Saloranta */ public class JsonFactory implements Versioned, java.io.Serializable // since 2.1 (for Android, mostly) { /** * Computed for Jackson 2.1.0 release */ private static final long serialVersionUID = 8726401676402117450L; /** * Name used to identify JSON format * (and returned by {@link #getFormatName()} */ public final static String FORMAT_NAME_JSON = "JSON"; /** * Bitfield (set of flags) of all factory features that are enabled by default. */ protected final static int DEFAULT_FACTORY_FEATURE_FLAGS = JsonFactory.Feature.collectDefaults(); /** * Bitfield (set of flags) of all parser features that are enabled * by default. */ protected final static int DEFAULT_PARSER_FEATURE_FLAGS = JsonParser.Feature.collectDefaults(); /** * Bitfield (set of flags) of all generator features that are enabled * by default. */ protected final static int DEFAULT_GENERATOR_FEATURE_FLAGS = JsonGenerator.Feature.collectDefaults(); private final static SerializableString DEFAULT_ROOT_VALUE_SEPARATOR = DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR; /** * Enumeration that defines all on/off features that can only be * changed for {@link JsonFactory}. */ public enum Feature { // // // Symbol handling (interning etc) /** * Feature that determines whether JSON object field names are * to be canonicalized using {@link String#intern} or not: * if enabled, all field names will be intern()ed (and caller * can count on this being true for all such names); if disabled, * no intern()ing is done. There may still be basic * canonicalization (that is, same String will be used to represent * all identical object property names for a single document). *<p> * Note: this setting only has effect if * {@link #CANONICALIZE_FIELD_NAMES} is true -- otherwise no * canonicalization of any sort is done. *<p> * This setting is enabled by default. */ INTERN_FIELD_NAMES(true), /** * Feature that determines whether JSON object field names are * to be canonicalized (details of how canonicalization is done * then further specified by * {@link #INTERN_FIELD_NAMES}). *<p> * This setting is enabled by default. */ CANONICALIZE_FIELD_NAMES(true) ; /** * Whether feature is enabled or disabled by default. */ private final boolean _defaultState; /** * Method that calculates bit set (flags) of all features that * are enabled by default. */ public static int collectDefaults() { int flags = 0; for (Feature f : values()) { if (f.enabledByDefault()) { flags |= f.getMask(); } } return flags; } private Feature(boolean defaultState) { _defaultState = defaultState; } public boolean enabledByDefault() { return _defaultState; } public boolean enabledIn(int flags) { return (flags & getMask()) != 0; } public int getMask() { return (1 << ordinal()); } } /** * This <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference} * to a {@link BufferRecycler} used to provide a low-cost * buffer recycling between reader and writer instances. */ final protected static ThreadLocal<SoftReference<BufferRecycler>> _recyclerRef = new ThreadLocal<SoftReference<BufferRecycler>>(); /** * Each factory comes equipped with a shared root symbol table. * It should not be linked back to the original blueprint, to * avoid contents from leaking between factories. */ protected final transient CharsToNameCanonicalizer _rootCharSymbols = CharsToNameCanonicalizer.createRoot(); /** * Alternative to the basic symbol table, some stream-based * parsers use different name canonicalization method. *<p> * TODO: should clean up this; looks messy having 2 alternatives * with not very clear differences. */ protected final transient BytesToNameCanonicalizer _rootByteSymbols = BytesToNameCanonicalizer.createRoot(); /** * Object that implements conversion functionality between * Java objects and JSON content. For base JsonFactory implementation * usually not set by default, but can be explicitly set. * Sub-classes (like @link org.codehaus.jackson.map.MappingJsonFactory} * usually provide an implementation. */ protected ObjectCodec _objectCodec; /** * Currently enabled factory features. */ protected int _factoryFeatures = DEFAULT_FACTORY_FEATURE_FLAGS; /** * Currently enabled parser features. */ protected int _parserFeatures = DEFAULT_PARSER_FEATURE_FLAGS; /** * Currently enabled generator features. */ protected int _generatorFeatures = DEFAULT_GENERATOR_FEATURE_FLAGS; /** * Definition of custom character escapes to use for generators created * by this factory, if any. If null, standard data format specific * escapes are used. */ protected CharacterEscapes _characterEscapes; /** * Optional helper object that may decorate input sources, to do * additional processing on input during parsing. */ protected InputDecorator _inputDecorator; /** * Optional helper object that may decorate output object, to do * additional processing on output during content generation. */ protected OutputDecorator _outputDecorator; /** * Separator used between root-level values, if any; null indicates * "do not add separator". * Default separator is a single space character. * * @since 2.1 */ protected SerializableString _rootValueSeparator = DEFAULT_ROOT_VALUE_SEPARATOR; /** * Default constructor used to create factory instances. * Creation of a factory instance is a light-weight operation, * but it is still a good idea to reuse limited number of * factory instances (and quite often just a single instance): * factories are used as context for storing some reused * processing objects (such as symbol tables parsers use) * and this reuse only works within context of a single * factory instance. */ public JsonFactory() { this(null); } public JsonFactory(ObjectCodec oc) { _objectCodec = oc; } /** * Method for constructing a new {@link JsonFactory} that has * the same settings as this instance, but is otherwise * independent (i.e. nothing is actually shared, symbol tables * are separate). * Note that {@link ObjectCodec} reference is not copied but is * set to null; caller typically needs to set it after calling * this method. * * @since 2.1 */ public JsonFactory copy() { _checkInvalidCopy(JsonFactory.class); return new JsonFactory(null); } /** * @since 2.1 * @param exp */ protected void _checkInvalidCopy(Class<?> exp) { if (getClass() != exp) { throw new IllegalStateException("Failed copy(): "+getClass().getName() +" (version: "+version()+") does not override copy(); it has to"); } } /** * Method that we need to override to actually make restoration go * through constructors etc. * Also: must be overridden by sub-classes as well. */ protected Object readResolve() { return new JsonFactory(_objectCodec); } /** * Method that can be used to quickly check whether given schema * is something that parsers and/or generators constructed by this * factory could use. Note that this means possible use, at the level * of data format (i.e. schema is for same data format as parsers and * generators this factory constructs); individual schema instances * may have further usage restrictions. * * @since 2.1 */ public boolean canUseSchema(FormatSchema schema) { String ourFormat = getFormatName(); return (ourFormat != null) && ourFormat.equals(schema.getSchemaType()); } /** * Method that returns short textual id identifying format * this factory supports. *<p> * Note: sub-classes should override this method; default * implementation will return null for all sub-classes */ public String getFormatName() { /* Somewhat nasty check: since we can't make this abstract * (due to backwards compatibility concerns), need to prevent * format name "leakage" */ if (getClass() == JsonFactory.class) { return FORMAT_NAME_JSON; } return null; } public MatchStrength hasFormat(InputAccessor acc) throws IOException { // since we can't keep this abstract, only implement for "vanilla" instance if (getClass() == JsonFactory.class) { return hasJSONFormat(acc); } return null; } public boolean requiresCustomCodec() { return false; } /** * Helper method that can be called to determine if content accessed * using given accessor seems to be JSON content. */ protected MatchStrength hasJSONFormat(InputAccessor acc) throws IOException { return ByteSourceJsonBootstrapper.hasJSONFormat(acc); } // @Override public Version version() { return CoreVersion.instance.version(); } /** * Method for enabling or disabling specified parser feature * (check {@link JsonParser.Feature} for list of features) */ public final JsonFactory configure(JsonFactory.Feature f, boolean state) { return state ? enable(f) : disable(f); } /** * Method for enabling specified parser feature * (check {@link JsonFactory.Feature} for list of features) */ public JsonFactory enable(JsonFactory.Feature f) { _factoryFeatures |= f.getMask(); return this; } /** * Method for disabling specified parser features * (check {@link JsonFactory.Feature} for list of features) */ public JsonFactory disable(JsonFactory.Feature f) { _factoryFeatures &= ~f.getMask(); return this; } /** * Checked whether specified parser feature is enabled. */ public final boolean isEnabled(JsonFactory.Feature f) { return (_factoryFeatures & f.getMask()) != 0; } /** * Method for enabling or disabling specified parser feature * (check {@link JsonParser.Feature} for list of features) */ public final JsonFactory configure(JsonParser.Feature f, boolean state) { return state ? enable(f) : disable(f); } /** * Method for enabling specified parser feature * (check {@link JsonParser.Feature} for list of features) */ public JsonFactory enable(JsonParser.Feature f) { _parserFeatures |= f.getMask(); return this; } /** * Method for disabling specified parser features * (check {@link JsonParser.Feature} for list of features) */ public JsonFactory disable(JsonParser.Feature f) { _parserFeatures &= ~f.getMask(); return this; } /** * Checked whether specified parser feature is enabled. */ public final boolean isEnabled(JsonParser.Feature f) { return (_parserFeatures & f.getMask()) != 0; } /** * Method for getting currently configured input decorator (if any; * there is no default decorator). */ public InputDecorator getInputDecorator() { return _inputDecorator; } /** * Method for overriding currently configured input decorator */ public JsonFactory setInputDecorator(InputDecorator d) { _inputDecorator = d; return this; } /** * Method for enabling or disabling specified generator feature * (check {@link JsonGenerator.Feature} for list of features) */ public final JsonFactory configure(JsonGenerator.Feature f, boolean state) { return state ? enable(f) : disable(f); } /** * Method for enabling specified generator features * (check {@link JsonGenerator.Feature} for list of features) */ public JsonFactory enable(JsonGenerator.Feature f) { _generatorFeatures |= f.getMask(); return this; } /** * Method for disabling specified generator feature * (check {@link JsonGenerator.Feature} for list of features) */ public JsonFactory disable(JsonGenerator.Feature f) { _generatorFeatures &= ~f.getMask(); return this; } /** * Check whether specified generator feature is enabled. */ public final boolean isEnabled(JsonGenerator.Feature f) { return (_generatorFeatures & f.getMask()) != 0; } /** * Method for accessing custom escapes factory uses for {@link JsonGenerator}s * it creates. */ public CharacterEscapes getCharacterEscapes() { return _characterEscapes; } /** * Method for defining custom escapes factory uses for {@link JsonGenerator}s * it creates. */ public JsonFactory setCharacterEscapes(CharacterEscapes esc) { _characterEscapes = esc; return this; } /** * Method for getting currently configured output decorator (if any; * there is no default decorator). */ public OutputDecorator getOutputDecorator() { return _outputDecorator; } /** * Method for overriding currently configured output decorator */ public JsonFactory setOutputDecorator(OutputDecorator d) { _outputDecorator = d; return this; } /** * Method that allows overriding String used for separating root-level * JSON values (default is single space character) * * @param sep Separator to use, if any; null means that no separator is * automatically added * * @since 2.1 */ public JsonFactory setRootValueSeparator(String sep) { _rootValueSeparator = (sep == null) ? null : new SerializedString(sep); return this; } /** * @since 2.1 */ public String getRootValueSeparator() { return (_rootValueSeparator == null) ? null : _rootValueSeparator.getValue(); } /** * Method for associating a {@link ObjectCodec} (typically * a <code>com.fasterxml.jackson.databind.ObjectMapper</code>) * with this factory (and more importantly, parsers and generators * it constructs). This is needed to use data-binding methods * of {@link JsonParser} and {@link JsonGenerator} instances. */ public JsonFactory setCodec(ObjectCodec oc) { _objectCodec = oc; return this; } public ObjectCodec getCodec() { return _objectCodec; } /** * Method for constructing JSON parser instance to parse * contents of specified file. Encoding is auto-detected * from contents according to JSON specification recommended * mechanism. *<p> * Underlying input stream (needed for reading contents) * will be <b>owned</b> (and managed, i.e. closed as need be) by * the parser, since caller has no access to it. * * @param f File that contains JSON content to parse * * @since 2.1 */ @SuppressWarnings("resource") public JsonParser createParser(File f) throws IOException, JsonParseException { // true, since we create InputStream from File IOContext ctxt = _createContext(f, true); InputStream in = new FileInputStream(f); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { in = _inputDecorator.decorate(ctxt, in); } return _createParser(in, ctxt); } /** * Method for constructing JSON parser instance to parse * contents of resource reference by given URL. * Encoding is auto-detected * from contents according to JSON specification recommended * mechanism. *<p> * Underlying input stream (needed for reading contents) * will be <b>owned</b> (and managed, i.e. closed as need be) by * the parser, since caller has no access to it. * * @param url URL pointing to resource that contains JSON content to parse * * @since 2.1 */ public JsonParser createParser(URL url) throws IOException, JsonParseException { // true, since we create InputStream from URL IOContext ctxt = _createContext(url, true); InputStream in = _optimizedStreamFromURL(url); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { in = _inputDecorator.decorate(ctxt, in); } return _createParser(in, ctxt); } /** * Method for constructing JSON parser instance to parse * the contents accessed via specified input stream. *<p> * The input stream will <b>not be owned</b> by * the parser, it will still be managed (i.e. closed if * end-of-stream is reacher, or parser close method called) * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} * is enabled. *<p> * Note: no encoding argument is taken since it can always be * auto-detected as suggested by JSON RFC. * * @param in InputStream to use for reading JSON content to parse * * @since 2.1 */ public JsonParser createParser(InputStream in) throws IOException, JsonParseException { IOContext ctxt = _createContext(in, false); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { in = _inputDecorator.decorate(ctxt, in); } return _createParser(in, ctxt); } /** * Method for constructing parser for parsing * the contents accessed via specified Reader. <p> * The read stream will <b>not be owned</b> by * the parser, it will still be managed (i.e. closed if * end-of-stream is reacher, or parser close method called) * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} * is enabled. * * @param r Reader to use for reading JSON content to parse * * @since 2.1 */ public JsonParser createParser(Reader r) throws IOException, JsonParseException { // false -> we do NOT own Reader (did not create it) IOContext ctxt = _createContext(r, false); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { r = _inputDecorator.decorate(ctxt, r); } return _createParser(r, ctxt); } /** * Method for constructing parser for parsing * the contents of given byte array. * * @since 2.1 */ public JsonParser createParser(byte[] data) throws IOException, JsonParseException { IOContext ctxt = _createContext(data, true); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length); if (in != null) { return _createParser(in, ctxt); } } return _createParser(data, 0, data.length, ctxt); } /** * Method for constructing parser for parsing * the contents of given byte array. * * @param data Buffer that contains data to parse * @param offset Offset of the first data byte within buffer * @param len Length of contents to parse within buffer * * @since 2.1 */ public JsonParser createParser(byte[] data, int offset, int len) throws IOException, JsonParseException { IOContext ctxt = _createContext(data, true); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { InputStream in = _inputDecorator.decorate(ctxt, data, offset, len); if (in != null) { return _createParser(in, ctxt); } } return _createParser(data, offset, len, ctxt); } /** * Method for constructing parser for parsing * contents of given String. * * @since 2.1 */ public JsonParser createParser(String content) throws IOException, JsonParseException { Reader r = new StringReader(content); // true -> we own the Reader (and must close); not a big deal IOContext ctxt = _createContext(r, true); // [JACKSON-512]: allow wrapping with InputDecorator if (_inputDecorator != null) { r = _inputDecorator.decorate(ctxt, r); } return _createParser(r, ctxt); } /** * Method for constructing JSON parser instance to parse * contents of specified file. Encoding is auto-detected * from contents according to JSON specification recommended * mechanism. *<p> * Underlying input stream (needed for reading contents) * will be <b>owned</b> (and managed, i.e. closed as need be) by * the parser, since caller has no access to it. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @param f File that contains JSON content to parse * * @deprecated Since 2.2, use {@link #createParser(File)} instead. */ @Deprecated public JsonParser createJsonParser(File f) throws IOException, JsonParseException { return createParser(f); } /** * Method for constructing JSON parser instance to parse * contents of resource reference by given URL. * Encoding is auto-detected * from contents according to JSON specification recommended * mechanism. *<p> * Underlying input stream (needed for reading contents) * will be <b>owned</b> (and managed, i.e. closed as need be) by * the parser, since caller has no access to it. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @param url URL pointing to resource that contains JSON content to parse * * @deprecated Since 2.2, use {@link #createParser(URL)} instead. */ @Deprecated public JsonParser createJsonParser(URL url) throws IOException, JsonParseException { return createParser(url); } /** * Method for constructing JSON parser instance to parse * the contents accessed via specified input stream. *<p> * The input stream will <b>not be owned</b> by * the parser, it will still be managed (i.e. closed if * end-of-stream is reacher, or parser close method called) * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} * is enabled. *<p> * Note: no encoding argument is taken since it can always be * auto-detected as suggested by JSON RFC. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @param in InputStream to use for reading JSON content to parse * * @deprecated Since 2.2, use {@link #createParser(InputStream)} instead. */ @Deprecated public JsonParser createJsonParser(InputStream in) throws IOException, JsonParseException { return createParser(in); } /** * Method for constructing parser for parsing * the contents accessed via specified Reader. <p> * The read stream will <b>not be owned</b> by * the parser, it will still be managed (i.e. closed if * end-of-stream is reacher, or parser close method called) * if (and only if) {@link com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} * is enabled. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @param r Reader to use for reading JSON content to parse * * @deprecated Since 2.2, use {@link #createParser(Reader)} instead. */ @Deprecated public JsonParser createJsonParser(Reader r) throws IOException, JsonParseException { return createParser(r); } /** * Method for constructing parser for parsing * the contents of given byte array. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @deprecated Since 2.2, use {@link #createParser(byte[])} instead. */ @Deprecated public JsonParser createJsonParser(byte[] data) throws IOException, JsonParseException { return createParser(data); } /** * Method for constructing parser for parsing * the contents of given byte array. *<p> * NOTE: as of 2.1, should not be used (will be deprecated in 2.2); * instead, should call <code>createParser</code>. * * @param data Buffer that contains data to parse * @param offset Offset of the first data byte within buffer * @param len Length of contents to parse within buffer * * @deprecated Since 2.2, use {@link #createParser(byte[],int,int)} instead. */ @Deprecated public JsonParser createJsonParser(byte[] data, int offset, int len) throws IOException, JsonParseException { return createParser(data, offset, len); } /** * Method for constructing parser for parsing * contents of given String. * * @deprecated Since 2.2, use {@link #createParser(String)} instead. */ @Deprecated public JsonParser createJsonParser(String content) throws IOException, JsonParseException { return createParser(content); } /** * Method for constructing JSON generator for writing JSON content * using specified output stream. * Encoding to use must be specified, and needs to be one of available * types (as per JSON specification). *<p> * Underlying stream <b>is NOT owned</b> by the generator constructed, * so that generator will NOT close the output stream when * {@link JsonGenerator#close} is called (unless auto-closing * feature, * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} * is enabled). * Using application needs to close it explicitly if this is the case. *<p> * Note: there are formats that use fixed encoding (like most binary data formats) * and that ignore passed in encoding. * * @param out OutputStream to use for writing JSON content * @param enc Character encoding to use * * @since 2.1 */ public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException { // false -> we won't manage the stream unless explicitly directed to IOContext ctxt = _createContext(out, false); ctxt.setEncoding(enc); if (enc == JsonEncoding.UTF8) { // [JACKSON-512]: allow wrapping with _outputDecorator if (_outputDecorator != null) { out = _outputDecorator.decorate(ctxt, out); } return _createUTF8Generator(out, ctxt); } Writer w = _createWriter(out, enc, ctxt); // [JACKSON-512]: allow wrapping with _outputDecorator if (_outputDecorator != null) { w = _outputDecorator.decorate(ctxt, w); } return _createGenerator(w, ctxt); } /** * Convenience method for constructing generator that uses default * encoding of the format (UTF-8 for JSON and most other data formats). *<p> * Note: there are formats that use fixed encoding (like most binary data formats). * * @since 2.1 */ public JsonGenerator createGenerator(OutputStream out) throws IOException { return createGenerator(out, JsonEncoding.UTF8); } /** * Method for constructing JSON generator for writing JSON content * using specified Writer. *<p> * Underlying stream <b>is NOT owned</b> by the generator constructed, * so that generator will NOT close the Reader when * {@link JsonGenerator#close} is called (unless auto-closing * feature, * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). * Using application needs to close it explicitly. * * @since 2.1 * * @param out Writer to use for writing JSON content */ public JsonGenerator createGenerator(Writer out) throws IOException { IOContext ctxt = _createContext(out, false); // [JACKSON-512]: allow wrapping with _outputDecorator if (_outputDecorator != null) { out = _outputDecorator.decorate(ctxt, out); } return _createGenerator(out, ctxt); } /** * Method for constructing JSON generator for writing JSON content * to specified file, overwriting contents it might have (or creating * it if such file does not yet exist). * Encoding to use must be specified, and needs to be one of available * types (as per JSON specification). *<p> * Underlying stream <b>is owned</b> by the generator constructed, * i.e. generator will handle closing of file when * {@link JsonGenerator#close} is called. * * @param f File to write contents to * @param enc Character encoding to use * * @since 2.1 */ public JsonGenerator createGenerator(File f, JsonEncoding enc) throws IOException { OutputStream out = new FileOutputStream(f); // true -> yes, we have to manage the stream since we created it IOContext ctxt = _createContext(out, true); ctxt.setEncoding(enc); if (enc == JsonEncoding.UTF8) { // [JACKSON-512]: allow wrapping with _outputDecorator if (_outputDecorator != null) { out = _outputDecorator.decorate(ctxt, out); } return _createUTF8Generator(out, ctxt); } Writer w = _createWriter(out, enc, ctxt); // [JACKSON-512]: allow wrapping with _outputDecorator if (_outputDecorator != null) { w = _outputDecorator.decorate(ctxt, w); } return _createGenerator(w, ctxt); } /** * Method for constructing JSON generator for writing JSON content * using specified output stream. * Encoding to use must be specified, and needs to be one of available * types (as per JSON specification). *<p> * Underlying stream <b>is NOT owned</b> by the generator constructed, * so that generator will NOT close the output stream when * {@link JsonGenerator#close} is called (unless auto-closing * feature, * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} * is enabled). * Using application needs to close it explicitly if this is the case. *<p> * Note: there are formats that use fixed encoding (like most binary data formats) * and that ignore passed in encoding. * * @param out OutputStream to use for writing JSON content * @param enc Character encoding to use * * @deprecated Since 2.2, use {@link #createGenerator(OutputStream, JsonEncoding)} instead. */ @Deprecated public JsonGenerator createJsonGenerator(OutputStream out, JsonEncoding enc) throws IOException { return createGenerator(out, enc); } /** * Method for constructing JSON generator for writing JSON content * using specified Writer. *<p> * Underlying stream <b>is NOT owned</b> by the generator constructed, * so that generator will NOT close the Reader when * {@link JsonGenerator#close} is called (unless auto-closing * feature, * {@link com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). * Using application needs to close it explicitly. * * @param out Writer to use for writing JSON content * * @deprecated Since 2.2, use {@link #createGenerator(Writer)} instead. */ @Deprecated public JsonGenerator createJsonGenerator(Writer out) throws IOException { return createGenerator(out); } /** * Convenience method for constructing generator that uses default * encoding of the format (UTF-8 for JSON and most other data formats). *<p> * Note: there are formats that use fixed encoding (like most binary data formats). * * @deprecated Since 2.2, use {@link #createGenerator(OutputStream)} instead. */ @Deprecated public JsonGenerator createJsonGenerator(OutputStream out) throws IOException { return createGenerator(out, JsonEncoding.UTF8); } /** * Method for constructing JSON generator for writing JSON content * to specified file, overwriting contents it might have (or creating * it if such file does not yet exist). * Encoding to use must be specified, and needs to be one of available * types (as per JSON specification). *<p> * Underlying stream <b>is owned</b> by the generator constructed, * i.e. generator will handle closing of file when * {@link JsonGenerator#close} is called. * * @param f File to write contents to * @param enc Character encoding to use * * * @deprecated Since 2.2, use {@link #createGenerator(File,JsonEncoding)} instead. */ @Deprecated public JsonGenerator createJsonGenerator(File f, JsonEncoding enc) throws IOException { return createGenerator(f, enc); } /** * Overridable factory method that actually instantiates desired parser * given {@link InputStream} and context object. *<p> * This method is specifically designed to remain * compatible between minor versions so that sub-classes can count * on it being called as expected. That is, it is part of official * interface from sub-class perspective, although not a public * method available to users of factory implementations. * * @since 2.1 */ protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException, JsonParseException { // As per [JACKSON-259], may want to fully disable canonicalization: return new ByteSourceJsonBootstrapper(ctxt, in).constructParser(_parserFeatures, _objectCodec, _rootByteSymbols, _rootCharSymbols, isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES), isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES)); } /** * @deprecated since 2.1 -- use {@link #_createParser(InputStream, IOContext)} instead */ @Deprecated protected JsonParser _createJsonParser(InputStream in, IOContext ctxt) throws IOException, JsonParseException { return _createParser(in, ctxt); } /** * Overridable factory method that actually instantiates parser * using given {@link Reader} object for reading content. *<p> * This method is specifically designed to remain * compatible between minor versions so that sub-classes can count * on it being called as expected. That is, it is part of official * interface from sub-class perspective, although not a public * method available to users of factory implementations. * * @since 2.1 */ protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec, _rootCharSymbols.makeChild(isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES), isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES))); } /** * @deprecated since 2.1 -- use {@link #_createParser(Reader, IOContext)} instead */ @Deprecated protected JsonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException { return _createParser(r, ctxt); } /** * Overridable factory method that actually instantiates parser * using given {@link Reader} object for reading content * passed as raw byte array. *<p> * This method is specifically designed to remain * compatible between minor versions so that sub-classes can count * on it being called as expected. That is, it is part of official * interface from sub-class perspective, although not a public * method available to users of factory implementations. */ protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException, JsonParseException { return new ByteSourceJsonBootstrapper(ctxt, data, offset, len).constructParser(_parserFeatures, _objectCodec, _rootByteSymbols, _rootCharSymbols, isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES), isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES)); } /** * @deprecated since 2.1 -- use {@link #_createParser(byte[], int, int, IOContext)} instead */ @Deprecated protected JsonParser _createJsonParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException, JsonParseException { return _createParser(data, offset, len, ctxt); } /** * Overridable factory method that actually instantiates generator for * given {@link Writer} and context object. *<p> * This method is specifically designed to remain * compatible between minor versions so that sub-classes can count * on it being called as expected. That is, it is part of official * interface from sub-class perspective, although not a public * method available to users of factory implementations. */ protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException { WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt, _generatorFeatures, _objectCodec, out); if (_characterEscapes != null) { gen.setCharacterEscapes(_characterEscapes); } SerializableString rootSep = _rootValueSeparator; if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { gen.setRootValueSeparator(rootSep); } return gen; } /** * @deprecated since 2.1 -- use {@link #_createGenerator(Writer, IOContext)} instead */ @Deprecated protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt) throws IOException { /* NOTE: MUST call the deprecated method until it is deleted, just so * that override still works as expected, for now. */ return _createGenerator(out, ctxt); } /** * Overridable factory method that actually instantiates generator for * given {@link OutputStream} and context object, using UTF-8 encoding. *<p> * This method is specifically designed to remain * compatible between minor versions so that sub-classes can count * on it being called as expected. That is, it is part of official * interface from sub-class perspective, although not a public * method available to users of factory implementations. */ protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt, _generatorFeatures, _objectCodec, out); if (_characterEscapes != null) { gen.setCharacterEscapes(_characterEscapes); } SerializableString rootSep = _rootValueSeparator; if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { gen.setRootValueSeparator(rootSep); } return gen; } /** * @deprecated since 2.1 */ @Deprecated protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException { return _createUTF8Generator(out, ctxt); } protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException { // note: this should not get called any more (caller checks, dispatches) if (enc == JsonEncoding.UTF8) { // We have optimized writer for UTF-8 return new UTF8Writer(ctxt, out); } // not optimal, but should do unless we really care about UTF-16/32 encoding speed return new OutputStreamWriter(out, enc.getJavaName()); } /** * Overridable factory method that actually instantiates desired * context object. */ protected IOContext _createContext(Object srcRef, boolean resourceManaged) { return new IOContext(_getBufferRecycler(), srcRef, resourceManaged); } /** * Method used by factory to create buffer recycler instances * for parsers and generators. *<p> * Note: only public to give access for <code>ObjectMapper</code> */ public BufferRecycler _getBufferRecycler() { SoftReference<BufferRecycler> ref = _recyclerRef.get(); BufferRecycler br = (ref == null) ? null : ref.get(); if (br == null) { br = new BufferRecycler(); _recyclerRef.set(new SoftReference<BufferRecycler>(br)); } return br; } /** * Helper methods used for constructing an optimal stream for * parsers to use, when input is to be read from an URL. * This helps when reading file content via URL. */ protected InputStream _optimizedStreamFromURL(URL url) throws IOException { if ("file".equals(url.getProtocol())) { /* Can not do this if the path refers * to a network drive on windows. This fixes the problem; * might not be needed on all platforms (NFS?), but should not * matter a lot: performance penalty of extra wrapping is more * relevant when accessing local file system. */ String host = url.getHost(); if (host == null || host.length() == 0) { return new FileInputStream(url.getPath()); } } return url.openStream(); } }
package com.ftinc.lolserv.data.model; import com.ftinc.lolserv.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.Map; public class LolCommit implements ModelMap<LolCommit> { private static final Logger LOG = LoggerFactory.getLogger(LolCommit.class); /*********************************************************************************************** * * Static methods * */ /** * Get LolCommit from a parsed database map * * @param map * @return */ public static LolCommit createFromMap(Map<String, Object> map) { LolCommit commit = new LolCommit(); commit.id = (Long) map.get("id"); commit.message = (String) map.get("message"); commit.repo = (String) map.get("repo"); commit.authorName = (String) map.get("author_name"); commit.authorEmail = (String) map.get("author_email"); commit.commitHash = (String) map.get("hash"); commit.optionalKey = (String) map.get("optional_key"); commit.imageUrl = (String) map.get("image_url"); commit.timestamp = (long) map.get("timestamp"); return commit; } /*********************************************************************************************** * * Variables * */ public Long id; public String message; public String repo; public String authorName; public String authorEmail; public String commitHash; public String optionalKey; public String imageUrl; public transient byte[] imageData; public long timestamp; /*********************************************************************************************** * * Methods * */ /** * Save this object into the database, or update it if it already exists * * @param connection the database connection * @throws SQLException there was an error interfacing with the database */ public void save(Connection connection) throws SQLException { if(id == null){ String insert = "INSERT INTO commits (message,repo,author_name,author_email,hash,optional_key,image_url,timestamp) " + "VALUES (?,?,?,?,?,?,?,?)"; // Prepare the statement try(PreparedStatement stmt = connection.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS)){ // Set values stmt.setString(1, message); stmt.setString(2, repo); stmt.setString(3, authorName); stmt.setString(4, authorEmail); stmt.setString(5, commitHash); stmt.setString(6, optionalKey); stmt.setString(7, imageUrl); stmt.setLong(8, Utils.time()); int result = stmt.executeUpdate(); if(result > 0){ // Get generated keys try(ResultSet keys = stmt.getGeneratedKeys()){ if(keys.next()) { id = keys.getLong(1); LOG.info("Lolcommit[{}] was saved!", id); } } } } }else{ String update = "UPDATE commits SET message=?,repo=?,author_name=?,author_email=?,hash=?,optional_key=?,image_url=?,timestamp=? WHERE id=?"; try(PreparedStatement stmt = connection.prepareStatement(update)){ // Set values stmt.setString(1, message); stmt.setString(2, repo); stmt.setString(3, authorName); stmt.setString(4, authorEmail); stmt.setString(5, commitHash); stmt.setString(6, optionalKey); stmt.setString(7, imageUrl); stmt.setLong(8, Utils.time()); stmt.setLong(9, id); int result = stmt.executeUpdate(); if(result > 0){ LOG.info("Lolcommit[{}] was updated!", id); } } } } /** * Convert object into string representation */ @Override public String toString() { return String.format("Webhook [image: %s][repo: %s][message: %s][author: %s %s][commit: %s][opt: %s]", imageData.length, repo, message, authorName, authorEmail, commitHash, optionalKey); } /** * Get LolCommit from a parsed database map * * @param map * @return */ @Override public LolCommit fromMap(Map<String, Object> map) { id = (Long) map.get("id"); message = (String) map.get("message"); repo = (String) map.get("repo"); authorName = (String) map.get("author_name"); authorEmail = (String) map.get("author_email"); commitHash = (String) map.get("hash"); optionalKey = (String) map.get("optional_key"); imageUrl = (String) map.get("image_url"); timestamp = (int) map.get("timestamp"); return this; } /*********************************************************************************************** * * Builder * */ /** * Builder class */ public static class Builder{ private LolCommit lc; public Builder(){ lc = new LolCommit(); } public Builder message(String msg){ lc.message = msg; return this; } public Builder repo(String repo){ lc.repo = repo; return this; } public Builder author(String name, String email){ lc.authorName = name; lc.authorEmail = email; return this; } public Builder commit(String hash){ lc.commitHash = hash; return this; } public Builder opt(String optKey){ lc.optionalKey = optKey; return this; } public Builder image(byte[] data){ lc.imageData = data; return this; } public LolCommit build(){ return lc; } } }
package com.gitblit.wicket.pages; import java.io.Serializable; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.target.basic.RedirectRequestTarget; import com.gitblit.Keys; import com.gitblit.models.RepositoryModel; import com.gitblit.models.TicketModel; import com.gitblit.models.UserModel; import com.gitblit.models.TicketModel.Status; import com.gitblit.models.TicketModel.Type; import com.gitblit.tickets.ITicketService; import com.gitblit.tickets.QueryBuilder; import com.gitblit.tickets.QueryResult; import com.gitblit.tickets.TicketIndexer.Lucene; import com.gitblit.utils.ArrayUtils; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.GitBlitWebApp; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.SessionlessForm; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.GravatarImage; import com.gitblit.wicket.panels.LinkPanel; public class MyTicketsPage extends RootPage { public static final String [] openStatii = new String [] { Status.New.name().toLowerCase(), Status.Open.name().toLowerCase() }; public static final String [] closedStatii = new String [] { "!" + Status.New.name().toLowerCase(), "!" + Status.Open.name().toLowerCase() }; public MyTicketsPage() { this(null); } public MyTicketsPage(PageParameters params) { super(params); setupPage("", getString("gb.mytickets")); UserModel currentUser = GitBlitWebSession.get().getUser(); if (currentUser == null) { setRedirect(true); setResponsePage(getApplication().getHomePage()); return; } final String username = currentUser.getName(); final String[] statiiParam = (params == null) ? openStatii : params.getStringArray(Lucene.status.name()); final String assignedToParam = (params == null) ? "" : params.getString(Lucene.responsible.name(), null); final String milestoneParam = (params == null) ? "" : params.getString(Lucene.milestone.name(), null); final String queryParam = (params == null || StringUtils.isEmpty(params.getString("q", null))) ? "watchedby:" + username : params.getString("q", null); final String searchParam = (params == null) ? "" : params.getString("s", null); final String sortBy = (params == null) ? "" : Lucene.fromString(params.getString("sort", Lucene.created.name())).name(); final boolean desc = (params == null) ? true : !"asc".equals(params.getString("direction", "desc")); // add search form TicketSearchForm searchForm = new TicketSearchForm("ticketSearchForm", searchParam); add(searchForm); searchForm.setTranslatedAttributes(); // standard queries add(new BookmarkablePageLink<Void>("changesQuery", MyTicketsPage.class, queryParameters( Lucene.type.matches(TicketModel.Type.Proposal.name()), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("bugsQuery", MyTicketsPage.class, queryParameters( Lucene.type.matches(TicketModel.Type.Bug.name()), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("enhancementsQuery", MyTicketsPage.class, queryParameters( Lucene.type.matches(TicketModel.Type.Enhancement.name()), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("tasksQuery", MyTicketsPage.class, queryParameters( Lucene.type.matches(TicketModel.Type.Task.name()), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("questionsQuery", MyTicketsPage.class, queryParameters( Lucene.type.matches(TicketModel.Type.Question.name()), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("resetQuery", MyTicketsPage.class, queryParameters( null, milestoneParam, openStatii, null, null, true, 1))); add(new Label("userDivider")); add(new BookmarkablePageLink<Void>("createdQuery", MyTicketsPage.class, queryParameters( Lucene.createdby.matches(username), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("watchedQuery", MyTicketsPage.class, queryParameters( Lucene.watchedby.matches(username), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("mentionsQuery", MyTicketsPage.class, queryParameters( Lucene.mentions.matches(username), milestoneParam, statiiParam, assignedToParam, sortBy, desc, 1))); // states if (ArrayUtils.isEmpty(statiiParam)) { add(new Label("selectedStatii", getString("gb.all"))); } else { add(new Label("selectedStatii", StringUtils.flattenStrings(Arrays.asList(statiiParam), ","))); } add(new BookmarkablePageLink<Void>("openTickets", MyTicketsPage.class, queryParameters(queryParam, milestoneParam, openStatii, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("closedTickets", MyTicketsPage.class, queryParameters(queryParam, milestoneParam, closedStatii, assignedToParam, sortBy, desc, 1))); add(new BookmarkablePageLink<Void>("allTickets", MyTicketsPage.class, queryParameters(queryParam, milestoneParam, null, assignedToParam, sortBy, desc, 1))); // by status List<Status> statii = new ArrayList<Status>(Arrays.asList(Status.values())); statii.remove(Status.Closed); ListDataProvider<Status> resolutionsDp = new ListDataProvider<Status>(statii); DataView<Status> statiiLinks = new DataView<Status>("statii", resolutionsDp) { private static final long serialVersionUID = 1L; @Override public void populateItem(final Item<Status> item) { final Status status = item.getModelObject(); PageParameters p = queryParameters(queryParam, milestoneParam, new String [] { status.name().toLowerCase() }, assignedToParam, sortBy, desc, 1); String css = getStatusClass(status); item.add(new LinkPanel("statusLink", css, status.toString(), MyTicketsPage.class, p).setRenderBodyOnly(true)); } }; add(statiiLinks); List<TicketSort> sortChoices = new ArrayList<TicketSort>(); sortChoices.add(new TicketSort(getString("gb.sortNewest"), Lucene.created.name(), true)); sortChoices.add(new TicketSort(getString("gb.sortOldest"), Lucene.created.name(), false)); sortChoices.add(new TicketSort(getString("gb.sortMostRecentlyUpdated"), Lucene.updated.name(), true)); sortChoices.add(new TicketSort(getString("gb.sortLeastRecentlyUpdated"), Lucene.updated.name(), false)); sortChoices.add(new TicketSort(getString("gb.sortMostComments"), Lucene.comments.name(), true)); sortChoices.add(new TicketSort(getString("gb.sortLeastComments"), Lucene.comments.name(), false)); sortChoices.add(new TicketSort(getString("gb.sortMostPatchsetRevisions"), Lucene.patchsets.name(), true)); sortChoices.add(new TicketSort(getString("gb.sortLeastPatchsetRevisions"), Lucene.patchsets.name(), false)); sortChoices.add(new TicketSort(getString("gb.sortMostVotes"), Lucene.votes.name(), true)); sortChoices.add(new TicketSort(getString("gb.sortLeastVotes"), Lucene.votes.name(), false)); TicketSort currentSort = sortChoices.get(0); for (TicketSort ts : sortChoices) { if (ts.sortBy.equals(sortBy) && desc == ts.desc) { currentSort = ts; break; } } add(new Label("currentSort", currentSort.name)); ListDataProvider<TicketSort> sortChoicesDp = new ListDataProvider<TicketSort>(sortChoices); DataView<TicketSort> sortMenu = new DataView<TicketSort>("sort", sortChoicesDp) { private static final long serialVersionUID = 1L; @Override public void populateItem(final Item<TicketSort> item) { final TicketSort ts = item.getModelObject(); PageParameters params = queryParameters(queryParam, milestoneParam, statiiParam, assignedToParam, ts.sortBy, ts.desc, 1); item.add(new LinkPanel("sortLink", null, ts.name, MyTicketsPage.class, params).setRenderBodyOnly(true)); } }; add(sortMenu); // Build Query here QueryBuilder qb = new QueryBuilder(queryParam); if (!qb.containsField(Lucene.responsible.name())) { // specify the responsible qb.and(Lucene.responsible.matches(assignedToParam)); } if (!qb.containsField(Lucene.milestone.name())) { // specify the milestone qb.and(Lucene.milestone.matches(milestoneParam)); } if (!qb.containsField(Lucene.status.name()) && !ArrayUtils.isEmpty(statiiParam)) { // specify the states boolean not = false; QueryBuilder q = new QueryBuilder(); for (String state : statiiParam) { if (state.charAt(0) == '!') { not = true; q.and(Lucene.status.doesNotMatch(state.substring(1))); } else { q.or(Lucene.status.matches(state)); } } if (not) { qb.and(q.toString()); } else { qb.and(q.toSubquery().toString()); } } final String luceneQuery = qb.build(); // paging links int page = (params != null) ? Math.max(1, WicketUtils.getPage(params)) : 1; int pageSize = app().settings().getInteger(Keys.tickets.perPage, 25); ITicketService tickets = GitBlitWebApp.get().tickets(); List<QueryResult> results; if(StringUtils.isEmpty(searchParam)) { results = tickets.queryFor(luceneQuery, page, pageSize, sortBy, desc); } else { results = tickets.searchFor(null, searchParam, page, pageSize); } int totalResults = results.size() == 0 ? 0 : results.get(0).totalResults; buildPager(queryParam, milestoneParam, statiiParam, assignedToParam, sortBy, desc, page, pageSize, results.size(), totalResults); final ListDataProvider<QueryResult> dp = new ListDataProvider<QueryResult>(results); DataView<QueryResult> dataView = new DataView<QueryResult>("row", dp) { private static final long serialVersionUID = 1L; @Override protected void populateItem(Item<QueryResult> item) { QueryResult ticket = item.getModelObject(); RepositoryModel repository = app().repositories().getRepositoryModel(ticket.repository); Component swatch = new Label("repositorySwatch", "&nbsp;").setEscapeModelStrings(false); WicketUtils.setCssBackground(swatch, repository.toString()); item.add(swatch); PageParameters rp = WicketUtils.newRepositoryParameter(ticket.repository); PageParameters tp = WicketUtils.newObjectParameter(ticket.repository, "" + ticket.number); item.add(new LinkPanel("repositoryName", "list", StringUtils.stripDotGit(ticket.repository), SummaryPage.class, rp)); item.add(getStateIcon("ticketIcon", ticket.type, ticket.status)); item.add(new Label("ticketNumber", "" + ticket.number)); item.add(new LinkPanel("ticketTitle", "list", ticket.title, TicketsPage.class, tp)); // votes indicator Label v = new Label("ticketVotes", "" + ticket.votesCount); WicketUtils.setHtmlTooltip(v, getString("gb.votes")); item.add(v.setVisible(ticket.votesCount > 0)); Label ticketStatus = new Label("ticketStatus", ticket.status.toString()); String statusClass = getStatusClass(ticket.status); WicketUtils.setCssClass(ticketStatus, statusClass); item.add(ticketStatus); UserModel responsible = app().users().getUserModel(ticket.responsible); if (responsible == null) { if (ticket.responsible == null) { item.add(new Label("ticketResponsibleImg").setVisible(false)); } else { item.add(new GravatarImage("ticketResponsibleImg", ticket.responsible, ticket.responsible, null, 16, true)); } item.add(new Label("ticketResponsible", ticket.responsible)); } else { item.add(new GravatarImage("ticketResponsibleImg", responsible, null, 16, true)); item.add(new LinkPanel("ticketResponsible", null, responsible.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(ticket.responsible))); } } }; add(dataView); } protected Label getStateIcon(String wicketId, TicketModel ticket) { return getStateIcon(wicketId, ticket.type, ticket.status); } protected Label getStateIcon(String wicketId, Type type, Status state) { Label label = new Label(wicketId); if (type == null) { type = Type.defaultType; } switch (type) { case Proposal: WicketUtils.setCssClass(label, "fa fa-code-fork"); break; case Bug: WicketUtils.setCssClass(label, "fa fa-bug"); break; case Enhancement: WicketUtils.setCssClass(label, "fa fa-magic"); break; case Question: WicketUtils.setCssClass(label, "fa fa-question"); break; default: // standard ticket WicketUtils.setCssClass(label, "fa fa-ticket"); } WicketUtils.setHtmlTooltip(label, getTypeState(type, state)); return label; } protected String getTypeState(Type type, Status state) { return state.toString() + " " + type.toString(); } protected String getLozengeClass(Status status, boolean subtle) { if (status == null) { status = Status.New; } String css = ""; switch (status) { case Declined: case Duplicate: case Invalid: case Wontfix: case Abandoned: css = "aui-lozenge-error"; break; case Fixed: case Merged: case Resolved: css = "aui-lozenge-success"; break; case New: css = "aui-lozenge-complete"; break; case On_Hold: css = "aui-lozenge-current"; break; default: css = ""; break; } return "aui-lozenge" + (subtle ? " aui-lozenge-subtle": "") + (css.isEmpty() ? "" : " ") + css; } protected String getStatusClass(Status status) { String css = ""; switch (status) { case Declined: case Duplicate: case Invalid: case Wontfix: case Abandoned: css = "resolution-error"; break; case Fixed: case Merged: case Resolved: css = "resolution-success"; break; case New: css = "resolution-complete"; break; case On_Hold: css = "resolution-current"; break; default: css = ""; break; } return "resolution" + (css.isEmpty() ? "" : " ") + css; } private class TicketSort implements Serializable { private static final long serialVersionUID = 1L; final String name; final String sortBy; final boolean desc; TicketSort(String name, String sortBy, boolean desc) { this.name = name; this.sortBy = sortBy; this.desc = desc; } } private class TicketSearchForm extends SessionlessForm<Void> implements Serializable { private static final long serialVersionUID = 1L; private final IModel<String> searchBoxModel;; public TicketSearchForm(String id, String text) { super(id, MyTicketsPage.this.getClass(), MyTicketsPage.this.getPageParameters()); this.searchBoxModel = new Model<String>(text == null ? "" : text); TextField<String> searchBox = new TextField<String>("ticketSearchBox", searchBoxModel); add(searchBox); } void setTranslatedAttributes() { WicketUtils.setHtmlTooltip(get("ticketSearchBox"), MessageFormat.format(getString("gb.searchTicketsTooltip"), "")); WicketUtils.setInputPlaceholder(get("ticketSearchBox"), getString("gb.searchTickets")); } @Override public void onSubmit() { String searchString = searchBoxModel.getObject(); if (StringUtils.isEmpty(searchString)) { // redirect to self to avoid wicket page update bug String absoluteUrl = getCanonicalUrl(); getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl)); return; } // use an absolute url to workaround Wicket-Tomcat problems with // mounted url parameters (issue-111) PageParameters params = WicketUtils.newRepositoryParameter(""); params.add("s", searchString); String absoluteUrl = getCanonicalUrl(MyTicketsPage.class, params); getRequestCycle().setRequestTarget(new RedirectRequestTarget(absoluteUrl)); } } protected PageParameters queryParameters( String query, String milestone, String[] states, String assignedTo, String sort, boolean descending, int page) { PageParameters params = WicketUtils.newRepositoryParameter(""); if (!StringUtils.isEmpty(query)) { params.add("q", query); } if (!StringUtils.isEmpty(milestone)) { params.add(Lucene.milestone.name(), milestone); } if (!ArrayUtils.isEmpty(states)) { for (String state : states) { params.add(Lucene.status.name(), state); } } if (!StringUtils.isEmpty(assignedTo)) { params.add(Lucene.responsible.name(), assignedTo); } if (!StringUtils.isEmpty(sort)) { params.add("sort", sort); } if (!descending) { params.add("direction", "asc"); } if (page > 1) { params.add("pg", "" + page); } return params; } protected void buildPager( final String query, final String milestone, final String [] states, final String assignedTo, final String sort, final boolean desc, final int page, int pageSize, int count, int total) { boolean showNav = total > (2 * pageSize); boolean allowPrev = page > 1; boolean allowNext = (pageSize * (page - 1) + count) < total; add(new BookmarkablePageLink<Void>("prevLink", MyTicketsPage.class, queryParameters(query, milestone, states, assignedTo, sort, desc, page - 1)).setEnabled(allowPrev).setVisible(showNav)); add(new BookmarkablePageLink<Void>("nextLink", MyTicketsPage.class, queryParameters(query, milestone, states, assignedTo, sort, desc, page + 1)).setEnabled(allowNext).setVisible(showNav)); if (total <= pageSize) { add(new Label("pageLink").setVisible(false)); return; } // determine page numbers to display int pages = count == 0 ? 0 : ((total / pageSize) + (total % pageSize == 0 ? 0 : 1)); // preferred number of pagelinks int segments = 5; if (pages < segments) { // not enough data for preferred number of page links segments = pages; } int minpage = Math.min(Math.max(1, page - 2), pages - (segments - 1)); int maxpage = Math.min(pages, minpage + (segments - 1)); List<Integer> sequence = new ArrayList<Integer>(); for (int i = minpage; i <= maxpage; i++) { sequence.add(i); } ListDataProvider<Integer> pagesDp = new ListDataProvider<Integer>(sequence); DataView<Integer> pagesView = new DataView<Integer>("pageLink", pagesDp) { private static final long serialVersionUID = 1L; @Override public void populateItem(final Item<Integer> item) { final Integer i = item.getModelObject(); LinkPanel link = new LinkPanel("page", null, "" + i, MyTicketsPage.class, queryParameters(query, milestone, states, assignedTo, sort, desc, i)); link.setRenderBodyOnly(true); if (i == page) { WicketUtils.setCssClass(item, "active"); } item.add(link); } }; add(pagesView); } }
package com.github.anba.es6draft.parser; import static com.github.anba.es6draft.semantics.StaticSemantics.*; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.*; import com.github.anba.es6draft.ast.AbruptNode.Abrupt; import com.github.anba.es6draft.ast.*; import com.github.anba.es6draft.ast.MethodDefinition.MethodType; import com.github.anba.es6draft.parser.ParserException.ExceptionType; import com.github.anba.es6draft.regexp.RegExpParser; import com.github.anba.es6draft.runtime.internal.CompatibilityOption; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.SmallArrayList; import com.github.anba.es6draft.runtime.objects.FunctionPrototype; /** * Parser for ECMAScript6 source code * <ul> * <li>12 ECMAScript Language: Expressions * <li>13 ECMAScript Language: Statements and Declarations * <li>14 ECMAScript Language: Functions and Classes * <li>15 ECMAScript Language: Modules and Scripts * </ul> */ public class Parser { private static final boolean DEBUG = false; private static final int MAX_ARGUMENTS = FunctionPrototype.getMaxArguments(); private static final List<Binding> NO_INHERITED_BINDING = Collections.emptyList(); private static final Set<String> EMPTY_LABEL_SET = Collections.emptySet(); private final String sourceFile; private final int sourceLine; private final EnumSet<CompatibilityOption> options; private final EnumSet<Option> parserOptions; private TokenStream ts; private ParseContext context; private enum StrictMode { Unknown, Strict, NonStrict } private enum StatementType { Iteration, Breakable, Statement } private enum ContextKind { Script, Module, Function, Generator, ArrowFunction, GeneratorComprehension, Method; final boolean isScript() { return this == Script; } final boolean isModule() { return this == Module; } final boolean isFunction() { switch (this) { case ArrowFunction: case Function: case Generator: case GeneratorComprehension: case Method: return true; case Module: case Script: default: return false; } } } private static final class ParseContext { final ParseContext parent; final ContextKind kind; boolean superReference = false; boolean yieldAllowed = false; boolean returnAllowed = false; boolean noDivAfterYield = false; StrictMode strictMode = StrictMode.Unknown; boolean explicitStrict = false; ParserException strictError = null; List<FunctionNode> deferred = null; ArrayDeque<ObjectLiteral> objectLiterals = null; Map<String, LabelContext> labelSet = null; LabelContext labels = null; ScopeContext scopeContext; final TopContext topContext; final ScriptContext scriptContext; final ModuleContext modContext; final FunctionContext funContext; ParseContext() { this.parent = null; this.kind = null; this.topContext = null; this.scriptContext = null; this.modContext = null; this.funContext = null; } ParseContext(ParseContext parent, ContextKind kind) { this.parent = parent; this.kind = kind; if (kind.isScript()) { this.scriptContext = new ScriptContext(this); this.modContext = null; this.funContext = null; this.topContext = scriptContext; } else if (kind.isModule()) { this.scriptContext = null; this.modContext = new ModuleContext(this); this.funContext = null; this.topContext = modContext; } else { assert kind.isFunction(); this.scriptContext = null; this.modContext = null; this.funContext = new FunctionContext(this); this.topContext = funContext; } this.scopeContext = topContext; this.returnAllowed = kind.isFunction(); if (parent.strictMode == StrictMode.Strict) { this.strictMode = parent.strictMode; } } ParseContext findSuperContext() { ParseContext cx = this; while (cx.kind == ContextKind.ArrowFunction || cx.kind == ContextKind.GeneratorComprehension) { cx = cx.parent; } return cx; } void setReferencesSuper() { superReference = true; } boolean hasSuperReference() { return superReference; } int countLiterals() { return (objectLiterals != null ? objectLiterals.size() : 0); } void addLiteral(ObjectLiteral object) { if (objectLiterals == null) { objectLiterals = new ArrayDeque<>(4); } objectLiterals.push(object); } void removeLiteral(ObjectLiteral object) { objectLiterals.removeFirstOccurrence(object); } } private static final class FunctionContext extends TopContext implements FunctionScope { FunctionNode node = null; HashSet<String> parameterNames = null; FunctionContext(ParseContext context) { super(context); } @Override protected boolean isStrict() { return IsStrict(node); } @Override public FunctionNode getNode() { return node; } @Override public Set<String> parameterNames() { return parameterNames; } } private static final class ScriptContext extends TopContext implements ScriptScope { Script node = null; ScriptContext(ParseContext context) { super(context); } @Override protected boolean isStrict() { return IsStrict(node); } @Override public Script getNode() { return node; } } private static final class ModuleContext extends TopContext implements ModuleScope { LinkedHashSet<String> moduleRequests = new LinkedHashSet<>(); HashSet<String> exportBindings = new HashSet<>(); Module node = null; ModuleContext(ParseContext context) { super(context); } @Override protected boolean isStrict() { return true; } @Override public Module getNode() { return node; } @Override public Set<String> getModuleRequests() { return moduleRequests; } @Override public Set<String> getExportBindings() { return exportBindings; } void addModuleRequest(String moduleSpecifier) { moduleRequests.add(moduleSpecifier); } boolean addExportBinding(String binding) { return exportBindings.add(binding); } } private static abstract class TopContext extends ScopeContext implements TopLevelScope { final ScopeContext enclosing; boolean directEval = false; TopContext(ParseContext context) { super(null); this.enclosing = context.parent.scopeContext; } protected abstract boolean isStrict(); @Override public ScopeContext getEnclosingScope() { return enclosing; } @Override public boolean isDynamic() { return directEval && !isStrict(); } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public Set<String> varDeclaredNames() { return varDeclaredNames; } @Override public List<StatementListItem> varScopedDeclarations() { return varScopedDeclarations; } } private static final class BlockContext extends ScopeContext implements BlockScope { final boolean dynamic; ScopedNode node = null; BlockContext(ScopeContext parent, boolean dynamic) { super(parent); this.dynamic = dynamic; } @Override public ScopedNode getNode() { return node; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public boolean isDynamic() { return dynamic; } } private abstract static class ScopeContext implements Scope { final ScopeContext parent; HashSet<String> varDeclaredNames = null; HashSet<String> lexDeclaredNames = null; List<StatementListItem> varScopedDeclarations = null; List<Declaration> lexScopedDeclarations = null; ScopeContext(ScopeContext parent) { this.parent = parent; } @Override public Scope getParent() { return parent; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("var: ").append(varDeclaredNames != null ? varDeclaredNames : "<null>"); sb.append("\t"); sb.append("lex: ").append(lexDeclaredNames != null ? lexDeclaredNames : "<null>"); return sb.toString(); } boolean isTopLevel() { return (parent == null); } boolean addVarDeclaredName(String name) { if (varDeclaredNames == null) { varDeclaredNames = new HashSet<>(); } varDeclaredNames.add(name); return (lexDeclaredNames == null || !lexDeclaredNames.contains(name)); } boolean addLexDeclaredName(String name) { if (lexDeclaredNames == null) { lexDeclaredNames = new HashSet<>(); } return lexDeclaredNames.add(name) && (varDeclaredNames == null || !varDeclaredNames.contains(name)); } void addVarScopedDeclaration(StatementListItem decl) { if (varScopedDeclarations == null) { varScopedDeclarations = newSmallList(); } varScopedDeclarations.add(decl); } void addLexScopedDeclaration(Declaration decl) { if (lexScopedDeclarations == null) { lexScopedDeclarations = newSmallList(); } lexScopedDeclarations.add(decl); } } private static final class LabelContext { final LabelContext parent; final StatementType type; final Set<String> labelSet; final EnumSet<Abrupt> abrupts = EnumSet.noneOf(Abrupt.class); LabelContext(LabelContext parent, StatementType type, Set<String> labelSet) { this.parent = parent; this.type = type; this.labelSet = labelSet; } void mark(Abrupt abrupt) { abrupts.add(abrupt); } } @SuppressWarnings("serial") private static final class RetryGenerator extends RuntimeException { } public enum Option { Strict, FunctionCode, LocalScope, DirectEval, EvalScript, EnclosedByWithStatement; } public Parser(String sourceFile, int sourceLine, Set<CompatibilityOption> options) { this(sourceFile, sourceLine, options, EnumSet.noneOf(Option.class)); } public Parser(String sourceFile, int sourceLine, Set<CompatibilityOption> compatOptions, EnumSet<Option> options) { this.sourceFile = sourceFile; this.sourceLine = sourceLine; this.options = EnumSet.copyOf(compatOptions); this.parserOptions = EnumSet.copyOf(options); context = new ParseContext(); context.strictMode = this.parserOptions.contains(Option.Strict) ? StrictMode.Strict : StrictMode.NonStrict; } String getSourceFile() { return sourceFile; } int getSourceLine() { return sourceLine; } boolean isEnabled(CompatibilityOption option) { return options.contains(option); } boolean isEnabled(Option option) { return parserOptions.contains(option); } private ParseContext newContext(ContextKind kind) { return context = new ParseContext(context, kind); } private ParseContext restoreContext() { if (context.parent.strictError == null) { context.parent.strictError = context.strictError; } return context = context.parent; } private BlockContext enterWithContext() { BlockContext cx = new BlockContext(context.scopeContext, true); context.scopeContext = cx; return cx; } private ScopeContext exitWithContext() { return exitScopeContext(); } private BlockContext enterBlockContext() { BlockContext cx = new BlockContext(context.scopeContext, false); context.scopeContext = cx; return cx; } private BlockContext enterBlockContext(Binding binding) { BlockContext cx = enterBlockContext(); addLexDeclaredName(binding); return cx; } private BlockContext enterBlockContext(List<Binding> bindings) { BlockContext cx = enterBlockContext(); addLexDeclaredNames(bindings); return cx; } private ScopeContext exitBlockContext() { return exitScopeContext(); } private ScopeContext exitScopeContext() { ScopeContext scope = context.scopeContext; ScopeContext parent = scope.parent; assert parent != null : "exitScopeContext() on top-level"; HashSet<String> varDeclaredNames = scope.varDeclaredNames; if (varDeclaredNames != null) { scope.varDeclaredNames = null; for (String name : varDeclaredNames) { addVarDeclaredName(parent, name); } } return context.scopeContext = parent; } private void addFunctionDeclaration(FunctionDeclaration decl) { addDeclaration(decl, BoundName(decl.getIdentifier())); } private void addGeneratorDeclaration(GeneratorDeclaration decl) { addDeclaration(decl, BoundName(decl.getIdentifier())); } private <DECLARATION extends Declaration & FunctionNode> void addDeclaration(DECLARATION decl, String name) { ParseContext parentContext = context.parent; ScopeContext parentScope = parentContext.scopeContext; if (parentScope.isTopLevel() && !parentContext.kind.isModule()) { // top-level function declaration in scripts/functions context parentScope.addVarScopedDeclaration(decl); if (!parentScope.addVarDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } else { // lexical-scoped function declaration in module/block context parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } } private void addLexScopedDeclaration(Declaration decl) { context.scopeContext.addLexScopedDeclaration(decl); } private void addVarScopedDeclaration(VariableStatement decl) { context.topContext.addVarScopedDeclaration(decl); } private void addVarDeclaredName(ScopeContext scope, String name) { if (!scope.addVarDeclaredName(name)) { // FIXME: provide correct line/source information reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } private void addVarDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addVarDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } private void addLexDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addLexDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ private void addVarDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addVarDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addVarDeclaredName((BindingPattern) binding); } } private void addVarDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addVarDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addVarDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addVarDeclaredName(context.scopeContext, bindingPattern, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any * duplicate entries. * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ private void addLexDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addLexDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addLexDeclaredName((BindingPattern) binding); } } private void addLexDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addLexDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addLexDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addLexDeclaredName(context.scopeContext, bindingPattern, name); } } private void addLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { addLexDeclaredName(binding); } } private void removeLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { removeLexDeclaredName(binding); } } private void removeLexDeclaredName(Binding binding) { HashSet<String> lexDeclaredNames = context.scopeContext.lexDeclaredNames; if (binding instanceof BindingIdentifier) { BindingIdentifier bindingIdentifier = (BindingIdentifier) binding; String name = BoundName(bindingIdentifier); lexDeclaredNames.remove(name); } else { assert binding instanceof BindingPattern; BindingPattern bindingPattern = (BindingPattern) binding; for (String name : BoundNames(bindingPattern)) { lexDeclaredNames.remove(name); } } } private void addExportBindings(List<String> bindings) { for (String binding : bindings) { addExportBinding(binding); } } private void addExportBinding(String binding) { assert context.scopeContext == context.modContext : "not in module scope"; if (!context.modContext.addExportBinding(binding)) { // TODO: error location reportSyntaxError(Messages.Key.VariableRedeclaration, binding); } } private void addModuleRequest(String moduleSpecifier) { assert context.scopeContext == context.modContext : "not in module scope"; context.modContext.addModuleRequest(moduleSpecifier); } private LabelContext enterLabelled(long sourcePosition, StatementType type, Set<String> labelSet) { LabelContext cx = context.labels = new LabelContext(context.labels, type, labelSet); if (!labelSet.isEmpty() && context.labelSet == null) { context.labelSet = new HashMap<>(); } for (String label : labelSet) { if (context.labelSet.containsKey(label)) { reportSyntaxError(sourcePosition, Messages.Key.DuplicateLabel, label); } context.labelSet.put(label, cx); } return cx; } private LabelContext exitLabelled() { for (String label : context.labels.labelSet) { context.labelSet.remove(label); } return context.labels = context.labels.parent; } private LabelContext enterIteration(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Iteration, labelSet); } private void exitIteration() { exitLabelled(); } private LabelContext enterBreakable(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Breakable, labelSet); } private void exitBreakable() { exitLabelled(); } private LabelContext findContinueTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type == StatementType.Iteration : cx.labelSet.contains(label)) { return cx; } } return null; } private LabelContext findBreakTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type != StatementType.Statement : cx.labelSet.contains(label)) { return cx; } } return null; } private static <T> List<T> newSmallList() { return new SmallArrayList<>(); } private static <T> List<T> newList() { return new SmallArrayList<>(); } private static <T> List<T> merge(List<T> list1, List<T> list2) { if (!(list1.isEmpty() || list2.isEmpty())) { List<T> merged = new ArrayList<>(); merged.addAll(list1); merged.addAll(list2); return merged; } return list1.isEmpty() ? list2 : list1; } private static int toLine(long sourcePosition) { return (int) sourcePosition; } private static int toColumn(long sourcePosition) { return (int) (sourcePosition >>> 32); } private long beginSource() { // make columns 1-indexed return ((long) 1 << 32) | getSourceLine(); } private ParserException reportException(ParserException exception) { throw exception; } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(Token expected, Token actual) { throw reportTokenMismatch(expected.toString(), actual); } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenNotIdentifier(Token actual) { throw reportTokenMismatch("<identifier>", actual); } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenNotIdentifierName(Token actual) { throw reportTokenMismatch("<identifier-name>", actual); } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(String expected, Token actual) { long sourcePosition = ts.sourcePosition(); int line = toLine(sourcePosition), col = toColumn(sourcePosition); if (actual == Token.EOF) { throw new ParserEOFException(sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } throw new ParserException(ExceptionType.SyntaxError, sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } /** * Report parser error with the given type and position */ private ParserException reportError(ExceptionType type, long sourcePosition, Messages.Key messageKey, String... args) { int line = toLine(sourcePosition), column = toColumn(sourcePosition); throw new ParserException(type, sourceFile, line, column, messageKey, args); } /** * Report syntax error from the given position */ private ParserException reportSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { throw reportError(ExceptionType.SyntaxError, sourcePosition, messageKey, args); } /** * Report syntax error from the node's begin source-position */ private ParserException reportSyntaxError(Node node, Messages.Key messageKey, String... args) { throw reportSyntaxError(node.getBeginPosition(), messageKey, args); } /** * Report syntax error from tokenstream's current position */ private ParserException reportSyntaxError(Messages.Key messageKey, String... args) { throw reportSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Report (or store) strict-mode parser error with the given type and position */ private void reportStrictModeError(ExceptionType type, long sourcePosition, Messages.Key messageKey, String... args) { if (context.strictMode == StrictMode.Unknown) { if (context.strictError == null) { int line = toLine(sourcePosition), column = toColumn(sourcePosition); context.strictError = new ParserException(type, sourceFile, line, column, messageKey, args); } } else if (context.strictMode == StrictMode.Strict) { reportError(type, sourcePosition, messageKey, args); } } /** * Report (or store) strict-mode syntax error from the given position */ private void reportStrictModeSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { reportStrictModeError(ExceptionType.SyntaxError, sourcePosition, messageKey, args); } /** * Report (or store) strict-mode syntax error from the node's source-position */ private void reportStrictModeSyntaxError(Node node, Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(node.getBeginPosition(), messageKey, args); } /** * Report (or store) strict-mode syntax error from tokenstream's current position */ void reportStrictModeSyntaxError(Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Peeks the next token in the token-stream */ private Token peek() { return ts.peekToken(); } /** * Checks whether the next token in the token-stream is equal to the input token */ private boolean LOOKAHEAD(Token token) { return ts.peekToken() == token; } /** * Returns the current token in the token-stream */ private Token token() { return ts.currentToken(); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(Token tok) { if (tok != token()) reportTokenMismatch(tok, token()); Token next = ts.nextToken(); if (DEBUG) System.out.printf("consume(%s) -> %s\n", tok, next); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(String name) { long sourcePos = ts.sourcePosition(); String string = ts.getString(); consume(Token.NAME); if (!name.equals(string)) reportSyntaxError(sourcePos, Messages.Key.UnexpectedName, string, name); } public Script parseScript(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); ts = new TokenStream(this, new TokenStreamInput(source)); return script(); } public Module parseModule(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); ts = new TokenStream(this, new TokenStreamInput(source)); return module(); } public FunctionDefinition parseFunction(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); FunctionExpression function; newContext(ContextKind.Function); try { ts = new TokenStream(this, new TokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new TokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; function = new FunctionExpression(beginSource(), ts.endPosition(), scope, "anonymous", parameters, statements, context.hasSuperReference(), header, body); scope.node = function; function_EarlyErrors(function); function = inheritStrictness(function); } catch (RetryGenerator e) { // don't bother with legacy support here throw reportSyntaxError(Messages.Key.InvalidYieldExpression); } finally { restoreContext(); } createScript(new ExpressionStatement(function.getBeginPosition(), function.getEndPosition(), function)); return function; } finally { restoreContext(); } } public GeneratorDefinition parseGenerator(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); GeneratorExpression generator; newContext(ContextKind.Generator); try { ts = new TokenStream(this, new TokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new TokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function* anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; generator = new GeneratorExpression(beginSource(), ts.endPosition(), scope, "anonymous", parameters, statements, context.hasSuperReference(), header, body); scope.node = generator; generator_EarlyErrors(generator); generator = inheritStrictness(generator); } finally { restoreContext(); } createScript(new ExpressionStatement(generator.getBeginPosition(), generator.getEndPosition(), generator)); return generator; } finally { restoreContext(); } } private Script createScript(StatementListItem statement) { List<StatementListItem> statements = singletonList(statement); boolean strict = (context.strictMode == StrictMode.Strict); ScriptContext scope = context.scriptContext; Script script = new Script(beginSource(), ts.endPosition(), sourceFile, scope, statements, options, parserOptions, strict); scope.node = script; return script; } /** * <strong>[15.1] Scripts</strong> * * <pre> * Script : * ScriptBody<sub>opt</sub> * ScriptBody : * StatementList * </pre> */ private Script script() { newContext(ContextKind.Script); try { ts.initialise(); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = statementList(Token.EOF); List<StatementListItem> statements = merge(prologue, body); boolean strict = (context.strictMode == StrictMode.Strict); ScriptContext scope = context.scriptContext; Script script = new Script(beginSource(), ts.endPosition(), sourceFile, scope, statements, options, parserOptions, strict); scope.node = script; return script; } finally { restoreContext(); } } /** * <strong>[15.2] Modules</strong> * * <pre> * Module : * ModuleBody<sub>opt</sub> * ModuleBody : * ModuleItemList * </pre> */ private Module module() { newContext(ContextKind.Module); context.strictMode = StrictMode.Strict; try { ts.initialise(); List<ModuleItem> statements = moduleItemList(); ModuleContext scope = context.modContext; Module module = new Module(beginSource(), ts.endPosition(), sourceFile, scope, statements, options, parserOptions); scope.node = module; return module; } finally { restoreContext(); } } /** * <strong>[15.2] Modules</strong> * * <pre> * ModuleItemList : * ModuleItem * ModuleItemList ModuleItem * ModuleItem : * ImportDeclaration * ExportDeclaration * StatementListItem * </pre> */ private List<ModuleItem> moduleItemList() { List<ModuleItem> moduleItemList = newList(); while (token() != Token.EOF) { if (token() == Token.EXPORT) { moduleItemList.add(exportDeclaration()); } else if (token() == Token.IMPORT) { moduleItemList.add(importDeclaration()); } else if (isName("module") && isIdentifierReference(peek()) && noNextLineTerminator()) { moduleItemList.add(importDeclaration()); } else { moduleItemList.add(statementListItem()); } } return moduleItemList; } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ImportDeclaration : * ModuleImport * import ImportClause FromClause ; * import ModuleSpecifier ; * </pre> */ private ImportDeclaration importDeclaration() { long begin = ts.beginPosition(); if (token() != Token.IMPORT) { ModuleImport moduleImport = moduleImport(); // TODO: add lex declared return new ImportDeclaration(begin, ts.endPosition(), moduleImport); } else { consume(Token.IMPORT); if (token() != Token.STRING) { ImportClause importClause = importClause(); String moduleSpecifier = fromClause(); semicolon(); addModuleRequest(moduleSpecifier); if (importClause.getDefaultEntry() != null || !importClause.getNamedImports().isEmpty()) { // TODO: add lex declared } return new ImportDeclaration(begin, ts.endPosition(), importClause, moduleSpecifier); } else { String moduleSpecifier = moduleSpecifier(); semicolon(); addModuleRequest(moduleSpecifier); return new ImportDeclaration(begin, ts.endPosition(), moduleSpecifier); } } } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ModuleImport : * module [no <i>LineTerminator</i> here] ImportedBinding FromClause ; * </pre> */ private ModuleImport moduleImport() { long begin = ts.beginPosition(); consume("module"); if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } BindingIdentifier importedBinding = importedBinding(); String moduleSpecifier = fromClause(); semicolon(); addModuleRequest(moduleSpecifier); addLexDeclaredName(importedBinding); return new ModuleImport(begin, ts.endPosition(), importedBinding, moduleSpecifier); } /** * <strong>[15.2.1] Imports</strong> * * <pre> * FromClause : * from ModuleSpecifier * </pre> */ private String fromClause() { consume("from"); return moduleSpecifier(); } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ImportClause : * ImportedBinding * ImportedBinding , NamedImports * NamedImports * </pre> */ private ImportClause importClause() { long begin = ts.beginPosition(); BindingIdentifier defaultEntry = null; List<ImportSpecifier> namedImports = emptyList(); if (token() != Token.LC) { defaultEntry = importedBinding(); addLexDeclaredName(defaultEntry); if (token() == Token.COMMA) { consume(Token.COMMA); namedImports = namedImports(); } } else { namedImports = namedImports(); } return new ImportClause(begin, ts.endPosition(), defaultEntry, namedImports); } /** * <strong>[15.2.1] Imports</strong> * * <pre> * NamedImports : * { } * { ImportsList } * { ImportsList , } * ImportsList : * ImportSpecifier * ImportsList , ImportSpecifier * </pre> */ private List<ImportSpecifier> namedImports() { List<ImportSpecifier> namedImports = newList(); consume(Token.LC); while (token() != Token.RC) { namedImports.add(importSpecifier()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); return namedImports; } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ImportSpecifier : * ImportedBinding * IdentifierName as ImportedBinding * </pre> */ private ImportSpecifier importSpecifier() { assert context.strictMode != StrictMode.Unknown : "undefined strict-mode in import specifier"; long begin = ts.beginPosition(); String importName; BindingIdentifier localName; if (!isReservedWord(token())) { BindingIdentifier binding = importedBinding(); importName = binding.getName(); if (isName("as")) { consume("as"); localName = importedBinding(); } else { localName = binding; } } else { importName = identifierName(); consume("as"); localName = importedBinding(); } addLexDeclaredName(localName); return new ImportSpecifier(begin, ts.endPosition(), importName, localName); } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ModuleSpecifier : * StringLiteral * </pre> */ private String moduleSpecifier() { return stringLiteral(); } /** * <strong>[15.2.1] Imports</strong> * * <pre> * ImportedBinding : * BindingIdentifier * </pre> */ private BindingIdentifier importedBinding() { return bindingIdentifier(); } /** * <strong>[15.2.2] Exports</strong> * * <pre> * ExportDeclaration : * export * FromClause ; * export ExportsClause<sub>[NoReference]</sub> FromClause ; * export ExportsClause ; * export VariableStatement * export Declaration<sub>[Default]</sub> * export default AssignmentExpression ; * </pre> */ private ExportDeclaration exportDeclaration() { long begin = ts.beginPosition(); consume(Token.EXPORT); switch (token()) { case MUL: { // export * FromClause ; consume(Token.MUL); String moduleSpecifier = fromClause(); semicolon(); addModuleRequest(moduleSpecifier); return new ExportDeclaration(begin, ts.endPosition(), moduleSpecifier); } case LC: { // export ExportsClause[NoReference] FromClause ; // export ExportsClause ; long position = ts.position(), lineinfo = ts.lineinfo(); ExportsClause exportsClause = exportsClause(true); if (isName("from")) { String moduleSpecifier = fromClause(); semicolon(); addModuleRequest(moduleSpecifier); return new ExportDeclaration(begin, ts.endPosition(), exportsClause, moduleSpecifier); } ts.reset(position, lineinfo); exportsClause = exportsClause(false); semicolon(); return new ExportDeclaration(begin, ts.endPosition(), exportsClause); } case VAR: { // export VariableStatement VariableStatement variableStatement = variableStatement(); addExportBindings(BoundNames(variableStatement)); return new ExportDeclaration(begin, ts.endPosition(), variableStatement); } case FUNCTION: case CLASS: case CONST: case LET: { // export Declaration[Default] Declaration declaration = declaration(true); addExportBindings(BoundNames(declaration)); return new ExportDeclaration(begin, ts.endPosition(), declaration); } case DEFAULT: default: { // export default AssignmentExpression ; consume(Token.DEFAULT); Expression expression = assignmentExpression(true); semicolon(); // FIXME: default exports add a lexical declared name with value "default" (spec bug?) // BindingIdentifier id = new BindingIdentifier(beginPosition, ts.endPosition(), // "default"); // addLexDeclaredName(id); addExportBinding("default"); return new ExportDeclaration(begin, ts.endPosition(), expression); } } } /** * <strong>[15.2.2] Exports</strong> * * <pre> * ExportsClause<sub>[NoReference]</sub> : * { } * { ExportsList<sub>[?NoReference]</sub> } * { ExportsList<sub>[?NoReference]</sub> , } * ExportsList<sub>[NoReference]</sub> : * ExportSpecifier<sub>[?NoReference]</sub> * ExportsList<sub>[?NoReference]</sub> , ExportSpecifier<sub>[?NoReference]</sub> * </pre> */ private ExportsClause exportsClause(boolean noReference) { long begin = ts.beginPosition(); List<ExportSpecifier> exports = newList(); consume(Token.LC); while (token() != Token.RC) { exports.add(exportSpecifier(noReference)); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); return new ExportsClause(begin, ts.endPosition(), exports); } /** * <strong>[15.2.2] Exports</strong> * * <pre> * ExportSpecifier<sub>[NoReference]</sub> : * <sub>[~NoReference]</sub>IdentifierReference * <sub>[~NoReference]</sub>IdentifierReference as IdentifierName * <sub>[+NoReference]</sub>IdentifierName * <sub>[+NoReference]</sub>IdentifierName as IdentifierName * </pre> */ private ExportSpecifier exportSpecifier(boolean noReference) { long begin = ts.beginPosition(); String importName, localName, exportName; if (noReference) { String sourceName = identifierName(); if (isName("as")) { consume("as"); exportName = identifierName(); } else { exportName = sourceName; } importName = sourceName; localName = null; } else { importName = null; localName = identifierReference(); if (isName("as")) { consume("as"); exportName = identifierName(); } else { exportName = localName; } } addExportBinding(exportName); return new ExportSpecifier(begin, ts.endPosition(), importName, localName, exportName); } /** * <strong>[15.3] Directive Prologues and the Use Strict Directive</strong> * * <pre> * DirectivePrologue : * Directive<sub>opt</sub> * Directive: * StringLiteral ; * Directive StringLiteral ; * </pre> */ private List<StatementListItem> directivePrologue() { List<StatementListItem> statements = newSmallList(); boolean strict = false; directive: while (token() == Token.STRING) { long begin = ts.beginPosition(); boolean hasEscape = ts.hasEscape(); // peek() may clear hasEscape flag Token next = peek(); switch (next) { case SEMI: case RC: case EOF: break; default: if (noNextLineTerminator() || stringLiteralFollowSetNextLine(next)) { break directive; } break; } // found a directive String string = stringLiteral(); if (!hasEscape && "use strict".equals(string)) { strict = true; } StringLiteral stringLiteral = new StringLiteral(begin, ts.endPosition(), string); semicolon(); statements.add(new ExpressionStatement(begin, ts.endPosition(), stringLiteral)); } applyStrictMode(strict); return statements; } private static boolean stringLiteralFollowSetNextLine(Token token) { switch (token) { case DOT: case LB: case LP: case TEMPLATE: case COMMA: case HOOK: return true; default: return Token.isBinaryOperator(token) || Token.isAssignmentOperator(token); } } private void applyStrictMode(boolean strict) { if (strict) { context.strictMode = StrictMode.Strict; context.explicitStrict = true; if (context.strictError != null) { reportException(context.strictError); } } else { if (context.strictMode == StrictMode.Unknown) { context.strictMode = context.parent.strictMode; } } } private static FunctionNode.StrictMode toFunctionStrictness(boolean strict, boolean explicit) { if (!strict) { return FunctionNode.StrictMode.NonStrict; } if (explicit) { return FunctionNode.StrictMode.ExplicitStrict; } return FunctionNode.StrictMode.ImplicitStrict; } private <FUNCTION extends FunctionNode> FUNCTION inheritStrictness(FUNCTION function) { if (context.strictMode != StrictMode.Unknown) { boolean strict = (context.strictMode == StrictMode.Strict); function.setStrictMode(toFunctionStrictness(strict, context.explicitStrict)); if (context.deferred != null) { for (FunctionNode func : context.deferred) { func.setStrictMode(toFunctionStrictness(strict, false)); } context.deferred = null; } } else { // this case only applies for functions with default parameters assert context.parent.strictMode == StrictMode.Unknown; ParseContext parent = context.parent; if (parent.deferred == null) { parent.deferred = newSmallList(); } parent.deferred.add(function); if (context.deferred != null) { parent.deferred.addAll(context.deferred); context.deferred = null; } } return function; } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionDeclaration<sub>[Default]</sub> : * function BindingIdentifier<sub>[?Default]</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionDeclaration functionDeclaration(boolean allowDefault) { newContext(ContextKind.Function); try { long begin = ts.beginPosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = bindingIdentifierFunctionName(allowDefault); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(CompatibilityOption.ExpressionClosure)) { int startBody = ts.position(); statements = expressionClosureBody(); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionDeclaration function = new FunctionDeclaration(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); scope.node = function; function_EarlyErrors(function); addFunctionDeclaration(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionExpression : * function BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionExpression functionExpression() { newContext(ContextKind.Function); try { long begin = ts.beginPosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(false); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(CompatibilityOption.ExpressionClosure)) { int startBody = ts.position(); statements = expressionClosureBody(); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionExpression function = new FunctionExpression(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); scope.node = function; function_EarlyErrors(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * StrictFormalParameters : * FormalParameters * </pre> */ private FormalParameterList strictFormalParameters(Token end) { return formalParameters(end); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameters : * [empty] * FormalParameterList * </pre> */ private FormalParameterList formalParameters(Token end) { if (token() == end) { return new FormalParameterList(ts.beginPosition(), ts.endPosition(), Collections.<FormalParameter> emptyList()); } return formalParameterList(); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameterList : * FunctionRestParameter * FormalsList * FormalsList, FunctionRestParameter * FormalsList : * FormalParameter * FormalsList, FormalParameter * FunctionRestParameter : * BindingRestElement * FormalParameter : * BindingElement * </pre> */ private FormalParameterList formalParameterList() { long begin = ts.beginPosition(); List<FormalParameter> formals = newSmallList(); for (;;) { if (token() == Token.TRIPLE_DOT) { formals.add(bindingRestElementStrict()); break; } else { formals.add(bindingElement()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } } return new FormalParameterList(begin, ts.endPosition(), formals); } private static <T> T containsAny(Set<T> set, List<T> list) { for (T element : list) { if (set.contains(element)) { return element; } } return null; } private void checkFormalParameterRedeclaration(FunctionNode node, List<String> boundNames, HashSet<String> declaredNames) { if (!(declaredNames == null || declaredNames.isEmpty())) { String redeclared = containsAny(declaredNames, boundNames); if (redeclared != null) { reportSyntaxError(node, Messages.Key.FormalParameterRedeclaration, redeclared); } } } /** * 14.1.1 Static Semantics: Early Errors */ private void function_EarlyErrors(FunctionDefinition function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean strict = (context.strictMode != StrictMode.NonStrict); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); if (strict) { strictFormalParameters_EarlyErrors(function, boundNames, scope.parameterNames, simple); } else { formalParameters_EarlyErrors(function, boundNames, scope.parameterNames, simple); } } /** * 14.1.1 Static Semantics: Early Errors */ private void strictFormalParameters_EarlyErrors(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean hasDuplicates = (boundNames.size() != names.size()); if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } formalParameters_EarlyErrors(node, boundNames, names, simple); } /** * 14.1.1 Static Semantics: Early Errors */ private void formalParameters_EarlyErrors(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { if (!simple) { boolean hasDuplicates = (boundNames.size() != names.size()); if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionBody<sub>[Yield]</sub> : * FunctionStatementList<sub>[?Yield]</sub> * FunctionStatementList<sub>[Yield]</sub> : * StatementList<sub>[?Yield, Return]opt</sub> * </pre> */ private List<StatementListItem> functionBody(Token end) { // enable 'yield' if in generator context.yieldAllowed = (context.kind == ContextKind.Generator); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = statementList(end); return merge(prologue, body); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * ExpressionClosureBody<sub>[Yield]</sub> : * AssignmentExpression<sub>[In, ?Yield]</sub> * </pre> */ private List<StatementListItem> expressionClosureBody() { // need to call manually b/c directivePrologue() isn't used here applyStrictMode(false); Expression expr = assignmentExpression(true); return Collections.<StatementListItem> singletonList(new ReturnStatement( ts.beginPosition(), ts.endPosition(), expr)); } /** * <strong>[14.2] Arrow Function Definitions</strong> * * <pre> * ArrowFunction<sub>[In]</sub> : * ArrowParameters => ConciseBody<sub>[?In]</sub> * ArrowParameters : * BindingIdentifier * CoverParenthesisedExpressionAndArrowParameterList * ConciseBody<sub>[In]</sub> : * [LA &#x2209; { <b>{</b> }] AssignmentExpression<sub>[?In]</sub> * { FunctionBody } * </pre> * * <h2>Supplemental Syntax</h2> * * <pre> * ArrowFormalParameters : * ( StrictFormalParameters ) * </pre> */ private ArrowFunction arrowFunction(boolean allowIn) { newContext(ContextKind.ArrowFunction); try { long begin = ts.beginPosition(); StringBuilder source = new StringBuilder(); source.append("function anonymous"); FormalParameterList parameters; if (token() == Token.LP) { consume(Token.LP); int start = ts.position() - 1; // handle `YieldExpression = yield RegExp` in ArrowParameters context.noDivAfterYield = context.parent.kind == ContextKind.Generator; parameters = strictFormalParameters(Token.RP); context.noDivAfterYield = false; consume(Token.RP); source.append(ts.range(start, ts.position())); } else { BindingIdentifier identifier = bindingIdentifier(); FormalParameter parameter = new BindingElement(begin, ts.endPosition(), identifier, null); parameters = new FormalParameterList(begin, ts.endPosition(), singletonList(parameter)); source.append('(').append(identifier.getName()).append(')'); } consume(Token.ARROW); if (token() == Token.LC) { consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = source.toString(); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(begin, ts.endPosition(), scope, parameters, statements, header, body); scope.node = function; arrowFunction_EarlyErrors(function); return inheritStrictness(function); } else { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); Expression expression = assignmentExpression(allowIn); int endFunction = ts.position(); String header = source.toString(); String body = "return " + ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(begin, ts.endPosition(), scope, parameters, expression, header, body); scope.node = function; arrowFunction_EarlyErrors(function); return inheritStrictness(function); } } finally { restoreContext(); } } /** * 14.2.1 Static Semantics: Early Errors */ private void arrowFunction_EarlyErrors(ArrowFunction function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); strictFormalParameters_EarlyErrors(function, boundNames, scope.parameterNames, simple); } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * GeneratorMethod * get PropertyName ( ) { FunctionBody } * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition methodDefinition(boolean alwaysStrict) { switch (methodType()) { case Generator: return generatorMethod(alwaysStrict); case Getter: return getterMethod(alwaysStrict); case Setter: return setterMethod(alwaysStrict); case Function: default: return normalMethod(alwaysStrict); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * </pre> */ private MethodDefinition normalMethod(boolean alwaysStrict) { long begin = ts.beginPosition(); PropertyName propertyName = propertyName(); return normalMethod(begin, propertyName, alwaysStrict); } private MethodDefinition normalMethod(long begin, PropertyName propertyName, boolean alwaysStrict) { newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Function; MethodDefinition method = new MethodDefinition(begin, ts.endPosition(), scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_EarlyErrors(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * get PropertyName ( ) { FunctionBody } * </pre> */ private MethodDefinition getterMethod(boolean alwaysStrict) { long begin = ts.beginPosition(); consume(Token.NAME); // "get" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = new FormalParameterList(ts.beginPosition(), ts.endPosition(), Collections.<FormalParameter> emptyList()); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(CompatibilityOption.ExpressionClosure)) { int startBody = ts.position(); statements = expressionClosureBody(); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Getter; MethodDefinition method = new MethodDefinition(begin, ts.endPosition(), scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_EarlyErrors(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition setterMethod(boolean alwaysStrict) { long begin = ts.beginPosition(); consume(Token.NAME); // "set" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = propertySetParameterList(); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(CompatibilityOption.ExpressionClosure)) { int startBody = ts.position(); statements = expressionClosureBody(); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Setter; MethodDefinition method = new MethodDefinition(begin, ts.endPosition(), scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_EarlyErrors(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * PropertySetParameterList : * BindingIdentifier * BindingPattern * </pre> */ private FormalParameterList propertySetParameterList() { long begin = ts.beginPosition(); Binding binding = binding(); FormalParameter setParameter = new BindingElement(begin, ts.endPosition(), binding, null); return new FormalParameterList(begin, ts.endPosition(), singletonList(setParameter)); } private MethodType methodType() { if (token() == Token.MUL) { return MethodType.Generator; } if (token() == Token.NAME) { String name = getName(Token.NAME); if (("get".equals(name) || "set".equals(name)) && isPropertyName(peek())) { return "get".equals(name) ? MethodType.Getter : MethodType.Setter; } } return MethodType.Function; } private boolean isPropertyName(Token token) { return token == Token.STRING || token == Token.NUMBER || token == Token.LB || isIdentifierName(token); } /** * 14.3.1 Static Semantics: Early Errors */ private void methodDefinition_EarlyErrors(MethodDefinition method) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = method.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); switch (method.getType()) { case Function: case Generator: { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); strictFormalParameters_EarlyErrors(method, boundNames, scope.parameterNames, simple); return; } case Setter: { if (!simple) { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); propertySetParameterList_EarlyErrors(method, boundNames, scope.parameterNames, simple); return; } case Getter: default: return; } } /** * 14.3.1 Static Semantics: Early Errors */ private void propertySetParameterList_EarlyErrors(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (!simple && hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorMethod : * * PropertyName ( StrictFormalParameters ) { FunctionBody<sub>[Yield]</sub> } * </pre> */ private MethodDefinition generatorMethod(boolean alwaysStrict) { long begin = ts.beginPosition(); consume(Token.MUL); PropertyName propertyName = propertyName(); newContext(ContextKind.Generator); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function* " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Generator; MethodDefinition method = new MethodDefinition(begin, ts.endPosition(), scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_EarlyErrors(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorDeclaration<sub>[Default]</sub> : * function * BindingIdentifier<sub>[?Default]</sub> ( FormalParameters ) { FunctionBody<sub>[Yield]</sub> } * </pre> */ private GeneratorDeclaration generatorDeclaration(boolean allowDefault, boolean starless) { newContext(ContextKind.Generator); try { long begin = ts.beginPosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = bindingIdentifierFunctionName(allowDefault); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorDeclaration generator; if (!starless) { generator = new GeneratorDeclaration(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); } else { generator = new LegacyGeneratorDeclaration(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); } scope.node = generator; generator_EarlyErrors(generator); addGeneratorDeclaration(generator); return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorExpression : * function * BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody<sub>[Yield]</sub> } * </pre> */ private GeneratorExpression generatorExpression(boolean starless) { newContext(ContextKind.Generator); try { long begin = ts.beginPosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(false); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorExpression generator; if (!starless) { generator = new GeneratorExpression(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); } else { generator = new LegacyGeneratorExpression(begin, ts.endPosition(), scope, identifier, parameters, statements, context.hasSuperReference(), header, body); } scope.node = generator; generator_EarlyErrors(generator); return inheritStrictness(generator); } finally { restoreContext(); } } /** * 14.4.1 Static Semantics: Early Errors */ private void generator_EarlyErrors(GeneratorDefinition generator) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = generator.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean strict = (context.strictMode != StrictMode.NonStrict); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(generator, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(generator, boundNames, scope.lexDeclaredNames); if (strict) { strictFormalParameters_EarlyErrors(generator, boundNames, scope.parameterNames, simple); } else { formalParameters_EarlyErrors(generator, boundNames, scope.parameterNames, simple); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * YieldExpression<sub>[In]</sub> : * yield * yield [no <i>LineTerminator</i> here] <font size="-1">[Lexical goal <i>InputElementRegExp</i>]</font> AssignmentExpression<sub>[?In, Yield]</sub> * yield [no <i>LineTerminator</i> here] * <font size="-1">[Lexical goal <i>InputElementRegExp</i>]</font> AssignmentExpression<sub>[?In, Yield]</sub> * </pre> */ private YieldExpression yieldExpression(boolean allowIn) { if (!context.yieldAllowed) { if (context.kind == ContextKind.Function && isEnabled(CompatibilityOption.LegacyGenerator)) { throw new RetryGenerator(); } reportSyntaxError(Messages.Key.InvalidYieldExpression); } long begin = ts.beginPosition(); consume(Token.YIELD); boolean delegatedYield = false; if (token() == Token.MUL) { if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } consume(Token.MUL); delegatedYield = true; } Expression expr; if (delegatedYield) { expr = assignmentExpression(allowIn); } else if (!isEnabled(CompatibilityOption.LegacyGenerator)) { // FIXME: take this path based on the actual generator type, not based on options if (noLineTerminator() && assignmentExpressionFirstSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } else { // slightly different rules for optional AssignmentExpression in legacy generators if (noLineTerminator() && !assignmentExpressionFollowSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } return new YieldExpression(begin, ts.endPosition(), delegatedYield, expr); } private boolean assignmentExpressionFirstSet(Token token) { // returns FIRST(AssignmentExpression) switch (token) { case YIELD: // FIRST(YieldExpression) return true; case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: // FIRST(UnaryExpression) return true; case SUPER: case NEW: // FIRST(LeftHandSideExpression) return true; case THIS: case NULL: case FALSE: case TRUE: case NUMBER: case STRING: case LB: case LC: case LP: case FUNCTION: case CLASS: case TEMPLATE: // FIRST(PrimaryExpression) return true; case DIV: case ASSIGN_DIV: // FIRST(RegularExpressionLiteral) return true; case NAME: case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: // FIRST(Identifier) return isIdentifierReference(token); default: return false; } } private boolean assignmentExpressionFollowSet(Token token) { // returns FOLLOW(AssignmentExpression) without { "of", "in", "for", "{" } // NB: not the exact follow set, consider `a = let(x=0)x++ ++`, but not relevant here switch (token) { case COLON: case COMMA: case RB: case RC: case RP: case SEMI: case EOF: return true; default: return false; } } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassDeclaration<sub>[Default]</sub> : * class BindingIdentifier<sub>[?Default]</sub> ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassDeclaration classDeclaration(boolean allowDefault) { long begin = ts.beginPosition(); consume(Token.CLASS); // 10.2.1 - ClassDeclaration and ClassExpression is always strict code BindingIdentifier name = bindingIdentifierClassName(allowDefault); Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = leftHandSideExpression(true); } consume(Token.LC); enterBlockContext(name); List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); exitBlockContext(); consume(Token.RC); ClassDeclaration decl = new ClassDeclaration(begin, ts.endPosition(), name, heritage, staticMethods, prototypeMethods); addLexDeclaredName(name); addLexScopedDeclaration(decl); return decl; } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassExpression : * class BindingIdentifier<sub>opt</sub> ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassExpression classExpression() { long begin = ts.beginPosition(); consume(Token.CLASS); BindingIdentifier name = null; if (token() != Token.EXTENDS && token() != Token.LC) { // 10.2.1 - ClassDeclaration and ClassExpression is always strict code name = bindingIdentifierClassName(false); } Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = leftHandSideExpression(true); } consume(Token.LC); if (name != null) { enterBlockContext(name); } List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); if (name != null) { exitBlockContext(); } consume(Token.RC); return new ClassExpression(begin, ts.endPosition(), name, heritage, staticMethods, prototypeMethods); } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassBody : * ClassElementList * ClassElementList : * ClassElement * ClassElementList ClassElement * ClassElement : * MethodDefinition * static MethodDefinition * ; * </pre> */ private void classBody(BindingIdentifier className, List<MethodDefinition> staticMethods, List<MethodDefinition> prototypeMethods) { while (token() != Token.RC) { if (token() == Token.SEMI) { consume(Token.SEMI); } else if (token() == Token.STATIC && !LOOKAHEAD(Token.LP)) { consume(Token.STATIC); staticMethods.add(methodDefinition(true)); } else { prototypeMethods.add(methodDefinition(true)); } } classBody_EarlyErrors(className, staticMethods, true); classBody_EarlyErrors(className, prototypeMethods, false); } /** * 14.5.1 Static Semantics: Early Errors */ private void classBody_EarlyErrors(BindingIdentifier className, List<MethodDefinition> defs, boolean isStatic) { final int VALUE = 0, GETTER = 1, SETTER = 2; Map<String, Integer> values = new HashMap<>(); for (MethodDefinition def : defs) { String key = PropName(def); if (key == null) { assert def.getPropertyName() instanceof ComputedPropertyName; continue; } if (isStatic) { if ("prototype".equals(key)) { reportSyntaxError(def, Messages.Key.InvalidPrototypeMethod); } } else { if ("constructor".equals(key) && SpecialMethod(def)) { reportSyntaxError(def, Messages.Key.InvalidConstructorMethod); } // Give the constructor a better for name for stacktraces if (className != null) { def.setFunctionName(className.getName()); } } MethodDefinition.MethodType type = def.getType(); final int kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : VALUE; if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[13] ECMAScript Language: Statements and Declarations</strong> * * <pre> * Statement<sub>[Yield, Return]</sub> : * BlockStatement<sub>[?Yield, ?Return]</sub> * VariableStatement<sub>[?Yield]</sub> * EmptyStatement * ExpressionStatement<sub>[?Yield]</sub> * IfStatement<sub>[?Yield, ?Return]</sub> * BreakableStatement<sub>[?Yield, ?Return]</sub> * ContinueStatement<sub>[?Yield]</sub> * BreakStatement<sub>[?Yield]</sub> * <sub>[+Return]</sub>ReturnStatement<sub>[?Yield]</sub> * WithStatement<sub>[?Yield, ?Return]</sub> * LabelledStatement<sub>[?Yield, ?Return]</sub> * ThrowStatement<sub>[?Yield]</sub> * TryStatement<sub>[?Yield, ?Return]</sub> * DebuggerStatement * * BreakableStatement<sub>[Yield, Return]</sub> : * IterationStatement<sub>[?Yield, ?Return]</sub> * SwitchStatement<sub>[?Yield, ?Return]</sub> * </pre> */ private Statement statement() { switch (token()) { case LC: return block(NO_INHERITED_BINDING); case VAR: return variableStatement(); case SEMI: return emptyStatement(); case IF: return ifStatement(); case FOR: return forStatement(EMPTY_LABEL_SET); case WHILE: return whileStatement(EMPTY_LABEL_SET); case DO: return doWhileStatement(EMPTY_LABEL_SET); case CONTINUE: return continueStatement(); case BREAK: return breakStatement(); case RETURN: return returnStatement(); case WITH: return withStatement(); case SWITCH: return switchStatement(EMPTY_LABEL_SET); case THROW: return throwStatement(); case TRY: return tryStatement(); case DEBUGGER: return debuggerStatement(); case LET: if (isEnabled(CompatibilityOption.LetStatement) || isEnabled(CompatibilityOption.LetExpression)) { return letStatement(); } // fall-through case YIELD: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case NAME: if (LOOKAHEAD(Token.COLON)) { return labelledStatement(); } default: } return expressionStatement(); } /** * <strong>[13.1] Block</strong> * * <pre> * BlockStatement<sub>[Yield, Return]</sub> : * Block<sub>[?Yield, ?Return]</sub> * Block<sub>[Yield, Return]</sub> : * { StatementList<sub>[?Yield, ?Return]opt</sub> } * </pre> */ private BlockStatement block(List<Binding> inherited) { long begin = ts.beginPosition(); consume(Token.LC); BlockContext scope = enterBlockContext(); if (!inherited.isEmpty()) { addLexDeclaredNames(inherited); } List<StatementListItem> list = statementList(Token.RC); if (!inherited.isEmpty()) { removeLexDeclaredNames(inherited); } exitBlockContext(); consume(Token.RC); BlockStatement block = new BlockStatement(begin, ts.endPosition(), scope, list); scope.node = block; return block; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementList<sub>[Yield, Return]</sub> : * StatementItem<sub>[?Yield, ?Return]</sub> * StatementList<sub>[?Yield, ?Return]</sub> StatementListItem<sub>[?Yield, ?Return]</sub> * </pre> */ private List<StatementListItem> statementList(Token end) { List<StatementListItem> list = newList(); while (token() != end) { list.add(statementListItem()); } return list; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementListItem<sub>[Yield, Return]</sub> : * Statement<sub>[?Yield, ?Return]</sub> * Declaration<sub>[?Yield]</sub> * </pre> */ private StatementListItem statementListItem() { switch (token()) { case FUNCTION: case CLASS: case CONST: return declaration(false); case LET: if (lexicalBindingFirstSet(peek())) { return declaration(false); } // 'let' as identifier, e.g. `let + 1` // fall-through default: return statement(); } } /** * <strong>[13] ECMAScript Language: Statements and Declarations</strong> * * <pre> * Declaration<sub>[Yield, Default]</sub> : * FunctionDeclaration<sub>[?Default]</sub> * GeneratorDeclaration<sub>[?Default]</sub> * ClassDeclaration<sub>[?Default]</sub> * LexicalDeclaration<sub>[In, ?Yield]</sub> * </pre> */ private Declaration declaration(boolean allowDefault) { switch (token()) { case FUNCTION: return functionOrGeneratorDeclaration(allowDefault); case CLASS: return classDeclaration(allowDefault); case LET: case CONST: return lexicalDeclaration(true); default: throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } private Declaration functionOrGeneratorDeclaration(boolean allowDefault) { if (LOOKAHEAD(Token.MUL)) { return generatorDeclaration(allowDefault, false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionDeclaration(allowDefault); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorDeclaration(allowDefault, true); } } } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalDeclaration<sub>[In, Yield]</sub> : * LetOrConst BindingList<sub>[?In, ?Yield]</sub> ; * LetOrConst : * let * const * </pre> */ private LexicalDeclaration lexicalDeclaration(boolean allowIn) { long begin = ts.beginPosition(); LexicalDeclaration.Type type; if (token() == Token.LET) { consume(Token.LET); type = LexicalDeclaration.Type.Let; } else { consume(Token.CONST); type = LexicalDeclaration.Type.Const; } List<LexicalBinding> list = bindingList((type == LexicalDeclaration.Type.Const), allowIn); if (allowIn) { // semicolon() not called if "in" not allowed, cf. forStatement() semicolon(); } LexicalDeclaration decl = new LexicalDeclaration(begin, ts.endPosition(), type, list); addLexScopedDeclaration(decl); return decl; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingList<sub>[In, Yield]</sub> : * LexicalBinding<sub>[?In, ?Yield]</sub> * BindingList<sub>[?In, ?Yield]</sub>, LexicalBinding<sub>[?In, ?Yield]</sub> * </pre> */ private List<LexicalBinding> bindingList(boolean isConst, boolean allowIn) { List<LexicalBinding> list = newSmallList(); list.add(lexicalBinding(isConst, allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(lexicalBinding(isConst, allowIn)); } return list; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalBinding<sub>[In, Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> Initialiser<sub>[?In, ?Yield]opt</sub> * BindingPattern<sub>[?Yield]</sub> Initialiser<sub>[?In, ?Yield]</sub> * </pre> */ private LexicalBinding lexicalBinding(boolean isConst, boolean allowIn) { long begin = ts.beginPosition(); Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(false); addLexDeclaredName(bindingPattern); if (token() == Token.ASSIGN || allowIn) { // make initialiser optional if `allowIn == false`, cf. validateFor{InOf} initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(false); addLexDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } else if (isConst && allowIn) { // `allowIn == false` indicates for-loop, cf. validateFor{InOf} reportSyntaxError(bindingIdentifier, Messages.Key.ConstMissingInitialiser); } binding = bindingIdentifier; } return new LexicalBinding(begin, ts.endPosition(), binding, initialiser); } /** * Returns {@code true} iff {@code token} is in the first-set of LexicalBinding */ private boolean lexicalBindingFirstSet(Token token) { switch (token) { default: if (!isIdentifierReference(token)) { return false; } case LB: case LC: return true; } } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier<sub>[Default, Yield]</sub> : * <sub>[+Default]</sub> default * <sub>[~Yield]</sub> yield * Identifier * </pre> */ private BindingIdentifier bindingIdentifier() { return bindingIdentifier(true); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier<sub>[Default, Yield]</sub> : * <sub>[+Default]</sub> default * <sub>[~Yield]</sub> yield * Identifier * </pre> */ private BindingIdentifier bindingIdentifier(boolean allowLet) { long begin = ts.beginPosition(); if (token() == Token.LET && !allowLet) { reportTokenNotIdentifier(Token.LET); } String identifier = identifierReference(); if (context.strictMode != StrictMode.NonStrict) { if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportStrictModeSyntaxError(begin, Messages.Key.StrictModeRestrictedIdentifier); } } return new BindingIdentifier(begin, ts.endPosition(), identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * <p> * Difference when compared to {@link #bindingIdentifier()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * BindingIdentifier<sub>[Default, Yield]</sub> : * <sub>[+Default]</sub> default * <sub>[~Yield]</sub> yield * Identifier * </pre> */ private BindingIdentifier bindingIdentifierStrict(boolean allowLet) { long begin = ts.beginPosition(); if (token() == Token.LET && !allowLet) { reportTokenNotIdentifier(Token.LET); } String identifier = identifierReference(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(begin, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(begin, ts.endPosition(), identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * <p> * Difference when compared to {@link #bindingIdentifier()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * BindingIdentifier<sub>[Default, Yield]</sub> : * <sub>[+Default]</sub> default * <sub>[~Yield]</sub> yield * Identifier * </pre> */ private BindingIdentifier bindingIdentifierClassName(boolean allowDefault) { long begin = ts.beginPosition(); if (allowDefault && token() == Token.DEFAULT) { consume(Token.DEFAULT); return new BindingIdentifier(begin, ts.endPosition(), getName(Token.DEFAULT)); } String identifier = strictIdentifierReference(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(begin, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(begin, ts.endPosition(), identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * <p> * Special case for {@link Token#YIELD} as {@link BindingIdentifier} in functions and generators * * <pre> * BindingIdentifier<sub>[Default, Yield]</sub> : * <sub>[+Default]</sub> default * <sub>[~Yield]</sub> yield * Identifier * </pre> */ private BindingIdentifier bindingIdentifierFunctionName(boolean allowDefault) { // FIXME: Preliminary solution to provide SpiderMonkey/V8 compatibility // 'yield' is always a keyword in strict-mode and in generators, but parse function name // in the context of the surrounding environment if (token() == Token.YIELD) { long begin = ts.beginPosition(); if (isYieldName(context.parent)) { consume(Token.YIELD); return new BindingIdentifier(begin, ts.endPosition(), getName(Token.YIELD)); } reportStrictModeSyntaxError(begin, Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); reportTokenNotIdentifier(Token.YIELD); } if (allowDefault && token() == Token.DEFAULT) { long begin = ts.beginPosition(); consume(Token.DEFAULT); return new BindingIdentifier(begin, ts.endPosition(), getName(Token.DEFAULT)); } return bindingIdentifier(); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * Initialiser<sub>[In, Yield]</sub> : * = AssignmentExpression<sub>[?In, ?Yield]</sub> * </pre> */ private Expression initialiser(boolean allowIn) { consume(Token.ASSIGN); return assignmentExpression(allowIn); } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableStatement<sub>[Yield]</sub> : * var VariableDeclarationList<sub>[In, ?Yield]</sub> ; * </pre> */ private VariableStatement variableStatement() { long begin = ts.beginPosition(); consume(Token.VAR); List<VariableDeclaration> decls = variableDeclarationList(true); semicolon(); VariableStatement varStmt = new VariableStatement(begin, ts.endPosition(), decls); addVarScopedDeclaration(varStmt); return varStmt; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclarationList<sub>[In, Yield]</sub> : * VariableDeclaration<sub>[?In, ?Yield]</sub> * VariableDeclarationList<sub>[?In, ?Yield]</sub> , VariableDeclaration<sub>[?In, ?Yield]</sub> * </pre> */ private List<VariableDeclaration> variableDeclarationList(boolean allowIn) { List<VariableDeclaration> list = newSmallList(); list.add(variableDeclaration(allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(variableDeclaration(allowIn)); } return list; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclaration<sub>[In, Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> Initialiser<sub>[?In, ?Yield]opt</sub> * BindingPattern<sub>[Yield]</sub> Initialiser<sub>[?In, ?Yield]</sub> * </pre> */ private VariableDeclaration variableDeclaration(boolean allowIn) { Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addVarDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false`, cf. forStatement() initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addVarDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } binding = bindingIdentifier; } return new VariableDeclaration(binding, initialiser); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingPattern<sub>[Yield, GeneratorParameter]</sub> : * ObjectBindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * ArrayBindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private BindingPattern bindingPattern() { return bindingPattern(true); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingPattern<sub>[Yield, GeneratorParameter]</sub> : * ObjectBindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * ArrayBindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private BindingPattern bindingPattern(boolean allowLet) { if (token() == Token.LC) { return objectBindingPattern(allowLet); } else { return arrayBindingPattern(allowLet); } } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * ObjectBindingPattern<sub>[Yield, GeneratorParameter]</sub> : * { } * { BindingPropertyList<sub>[?Yield, ?GeneratorParameter]</sub> } * { BindingPropertyList<sub>[?Yield, ?GeneratorParameter]</sub> , } * BindingPropertyList<sub>[Yield, GeneratorParameter]</sub> : * BindingProperty<sub>[?Yield, ?GeneratorParameter]</sub> * BindingPropertyList<sub>[?Yield, ?GeneratorParameter]</sub> , BindingProperty<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private ObjectBindingPattern objectBindingPattern(boolean allowLet) { long begin = ts.beginPosition(); List<BindingProperty> list = newSmallList(); consume(Token.LC); while (token() != Token.RC) { list.add(bindingProperty(allowLet)); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); objectBindingPattern_EarlyErrors(list); return new ObjectBindingPattern(begin, ts.endPosition(), list); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingProperty<sub>[Yield, GeneratorParameter]</sub> : * SingleNameBinding<sub>[?Yield, ?GeneratorParameter]</sub> * PropertyName<sub>[?Yield, ?GeneratorParameter]</sub> : BindingElement<sub>[?Yield, ?GeneratorParameter]</sub> * SingleNameBinding<sub>[Yield, GeneratorParameter]</sub> : * <sub>[+GeneratorParameter]</sub>BindingIdentifier<sub>[Yield]</sub> Initialiser<sub>[In]opt</sub> * <sub>[~GeneratorParameter]</sub>BindingIdentifier<sub>[?Yield]</sub> Initialiser<sub>[In, ?Yield]opt</sub> * </pre> */ private BindingProperty bindingProperty(boolean allowLet) { if (token() == Token.LB || LOOKAHEAD(Token.COLON)) { PropertyName propertyName = propertyName(); consume(Token.COLON); Binding binding; if (token() == Token.LC) { binding = objectBindingPattern(allowLet); } else if (token() == Token.LB) { binding = arrayBindingPattern(allowLet); } else { binding = bindingIdentifierStrict(allowLet); } Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(propertyName, binding, initialiser); } else { BindingIdentifier binding = bindingIdentifierStrict(allowLet); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(binding, initialiser); } } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * ArrayBindingPattern<sub>[Yield, GeneratorParameter]</sub> : * [ Elision<sub>opt</sub> BindingRestElement<sub>[?Yield, ?GeneratorParameter]opt</sub> ] * [ BindingElementList<sub>[?Yield, ?GeneratorParameter]</sub> ] * [ BindingElementList<sub>[?Yield, ?GeneratorParameter]</sub> , Elision<sub>opt</sub> BindingRestElement<sub>[?Yield, ?GeneratorParameter]opt</sub> ] * BindingElementList<sub>[Yield, GeneratorParameter]</sub> : * BindingElisionElement<sub>[?Yield, ?GeneratorParameter]</sub> * BindingElementList<sub>[?Yield, ?GeneratorParameter]</sub> , BindingElisionElement<sub>[?Yield, ?GeneratorParameter]</sub> * BindingElisionElement<sub>[Yield, GeneratorParameter]</sub>: * Elision<sub>opt</sub> BindingElement<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private ArrayBindingPattern arrayBindingPattern(boolean allowLet) { long begin = ts.beginPosition(); List<BindingElementItem> list = newSmallList(); consume(Token.LB); boolean needComma = false; Token tok; while ((tok = token()) != Token.RB) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new BindingElision(0, 0)); } else if (tok == Token.TRIPLE_DOT) { list.add(bindingRestElementStrict(allowLet)); break; } else { list.add(bindingElementStrict(allowLet)); needComma = true; } } consume(Token.RB); arrayBindingPattern_EarlyErrors(list); return new ArrayBindingPattern(begin, ts.endPosition(), list); } /** * <pre> * Binding<sub>[Yield, GeneratorParameter]</sub> : * BindingIdentifier<sub>[?Yield, ?GeneratorParameter]</sub> * BindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private Binding binding() { return binding(true); } /** * <pre> * Binding<sub>[Yield, GeneratorParameter]</sub> : * BindingIdentifier<sub>[?Yield, ?GeneratorParameter]</sub> * BindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private Binding binding(boolean allowLet) { switch (token()) { case LC: return objectBindingPattern(allowLet); case LB: return arrayBindingPattern(allowLet); default: return bindingIdentifier(allowLet); } } /** * Difference when compared to {@link #binding()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * Binding<sub>[Yield, GeneratorParameter]</sub> : * BindingIdentifier<sub>[?Yield, ?GeneratorParameter]</sub> * BindingPattern<sub>[?Yield, ?GeneratorParameter]</sub> * </pre> */ private Binding bindingStrict(boolean allowLet) { switch (token()) { case LC: return objectBindingPattern(allowLet); case LB: return arrayBindingPattern(allowLet); default: return bindingIdentifierStrict(allowLet); } } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingElement<sub>[Yield, GeneratorParameter]</sub> : * SingleNameBinding<sub>[?Yield, ?GeneratorParameter]</sub> * <sub>[+GeneratorParameter]</sub>BindingPattern<sub>[?Yield, GeneratorParameter]</sub> Initialiser<sub>[In]opt</sub> * <sub>[~GeneratorParameter]</sub>BindingPattern<sub>[?Yield]</sub> Initialiser<sub>[In, ?Yield]opt</sub> * </pre> */ private BindingElement bindingElement() { return bindingElement(true); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingElement<sub>[Yield, GeneratorParameter]</sub> : * SingleNameBinding<sub>[?Yield, ?GeneratorParameter]</sub> * <sub>[+GeneratorParameter]</sub>BindingPattern<sub>[?Yield, GeneratorParameter]</sub> Initialiser<sub>[In]opt</sub> * <sub>[~GeneratorParameter]</sub>BindingPattern<sub>[?Yield]</sub> Initialiser<sub>[In, ?Yield]opt</sub> * </pre> */ private BindingElement bindingElement(boolean allowLet) { long begin = ts.beginPosition(); Binding binding = binding(allowLet); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(begin, ts.endPosition(), binding, initialiser); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * <p> * Difference when compared to {@link #bindingElement()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * BindingElement<sub>[Yield, GeneratorParameter]</sub> : * SingleNameBinding<sub>[?Yield, ?GeneratorParameter]</sub> * <sub>[+GeneratorParameter]</sub>BindingPattern<sub>[?Yield, GeneratorParameter]</sub> Initialiser<sub>[In]opt</sub> * <sub>[~GeneratorParameter]</sub>BindingPattern<sub>[?Yield]</sub> Initialiser<sub>[In, ?Yield]opt</sub> * </pre> */ private BindingElement bindingElementStrict(boolean allowLet) { long begin = ts.beginPosition(); Binding binding = bindingStrict(allowLet); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(begin, ts.endPosition(), binding, initialiser); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * * <pre> * BindingRestElement<sub>[Yield, GeneratorParameter]</sub> : * <sub>[+GeneratorParameter]</sub>... BindingIdentifier<sub>[Yield]</sub> * <sub>[~GeneratorParameter]</sub>... BindingIdentifier<sub>[?Yield]</sub> * </pre> */ @SuppressWarnings("unused") private BindingRestElement bindingRestElement(boolean allowLet) { long begin = ts.beginPosition(); consume(Token.TRIPLE_DOT); BindingIdentifier identifier = bindingIdentifier(allowLet); return new BindingRestElement(begin, ts.endPosition(), identifier); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * <p> * Difference when compared to {@link #bindingRestElement()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * BindingRestElement<sub>[Yield, GeneratorParameter]</sub> : * <sub>[+GeneratorParameter]</sub>... BindingIdentifier<sub>[Yield]</sub> * <sub>[~GeneratorParameter]</sub>... BindingIdentifier<sub>[?Yield]</sub> * </pre> */ private BindingRestElement bindingRestElementStrict() { return bindingRestElementStrict(true); } /** * <strong>[13.2.3] Destructuring Binding Patterns</strong> * <p> * Difference when compared to {@link #bindingRestElement()}:<br> * Neither "arguments" nor "eval" is allowed. * * <pre> * BindingRestElement<sub>[Yield, GeneratorParameter]</sub> : * <sub>[+GeneratorParameter]</sub>... BindingIdentifier<sub>[Yield]</sub> * <sub>[~GeneratorParameter]</sub>... BindingIdentifier<sub>[?Yield]</sub> * </pre> */ private BindingRestElement bindingRestElementStrict(boolean allowLet) { long begin = ts.beginPosition(); consume(Token.TRIPLE_DOT); BindingIdentifier identifier = bindingIdentifierStrict(allowLet); return new BindingRestElement(begin, ts.endPosition(), identifier); } private static String BoundName(BindingIdentifier binding) { return binding.getName(); } private static String BoundName(BindingRestElement element) { return element.getBindingIdentifier().getName(); } /** * 13.2.3.1 Static Semantics: Early Errors */ private void objectBindingPattern_EarlyErrors(List<BindingProperty> list) { for (BindingProperty property : list) { // BindingProperty : PropertyName ':' BindingElement // BindingProperty : BindingIdentifier Initialiser<opt> Binding binding = property.getBinding(); if (binding instanceof BindingIdentifier) { String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert binding instanceof BindingPattern; assert property.getPropertyName() != null; // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) binding).getList()); // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) // binding).getElements()); } } } /** * 13.2.3.1 Static Semantics: Early Errors */ private void arrayBindingPattern_EarlyErrors(List<BindingElementItem> list) { for (BindingElementItem element : list) { if (element instanceof BindingElement) { Binding binding = ((BindingElement) element).getBinding(); if (binding instanceof ArrayBindingPattern) { // already done implicitly // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) binding) // .getElements()); } else if (binding instanceof ObjectBindingPattern) { // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) // binding).getList()); } else { assert (binding instanceof BindingIdentifier); String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } } else if (element instanceof BindingRestElement) { String name = BoundName(((BindingRestElement) element)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(element, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert element instanceof BindingElision; } } } /** * <strong>[13.3] Empty Statement</strong> * * <pre> * EmptyStatement: * ; * </pre> */ private EmptyStatement emptyStatement() { long begin = ts.sourcePosition(); consume(Token.SEMI); return new EmptyStatement(begin, ts.endPosition()); } /** * <strong>[13.4] Expression Statement</strong> * * <pre> * ExpressionStatement<sub>[Yield]</sub> : * [LA &#x2209; { <b>{, function, class, let [</b> }] Expression<sub>[In, ?Yield]</sub> ; * </pre> */ private ExpressionStatement expressionStatement() { switch (token()) { case LC: case FUNCTION: case CLASS: break; case LET: if (LOOKAHEAD(Token.LB)) { break; } default: long begin = ts.beginPosition(); Expression expr = expression(true); semicolon(); return new ExpressionStatement(begin, ts.endPosition(), expr); } throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } /** * <strong>[13.5] The <code>if</code> Statement</strong> * * <pre> * IfStatement<sub>[Yield, Return]</sub> : * if ( Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> else Statement<sub>[?Yield, ?Return]</sub> * if ( Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * </pre> */ private IfStatement ifStatement() { long begin = ts.beginPosition(); consume(Token.IF); consume(Token.LP); Expression test = expression(true); consume(Token.RP); Statement then = statement(); Statement otherwise = null; if (token() == Token.ELSE) { consume(Token.ELSE); otherwise = statement(); } return new IfStatement(begin, ts.endPosition(), test, then, otherwise); } /** * <strong>[13.6.1] The <code>do-while</code> Statement</strong> * * <pre> * IterationStatement<sub>[Yield, Return]</sub> : * do Statement<sub>[?Yield, ?Return]</sub> while ( Expression<sub>[In, ?Yield]</sub> ) ;<sub>opt</sub> * </pre> */ private DoWhileStatement doWhileStatement(Set<String> labelSet) { long begin = ts.beginPosition(); consume(Token.DO); LabelContext labelCx = enterIteration(begin, labelSet); Statement stmt = statement(); exitIteration(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); if (token() == Token.SEMI) { consume(Token.SEMI); } return new DoWhileStatement(begin, ts.endPosition(), labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.2] The <code>while</code> Statement</strong> * * <pre> * IterationStatement<sub>[Yield, Return]</sub> : * while ( Expression<sub>[In, ?Yield]</sub> ) StatementStatement<sub>[?Yield, ?Return]</sub> * </pre> */ private WhileStatement whileStatement(Set<String> labelSet) { long begin = ts.beginPosition(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); LabelContext labelCx = enterIteration(begin, labelSet); Statement stmt = statement(); exitIteration(); return new WhileStatement(begin, ts.endPosition(), labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.3] The <code>for</code> Statement</strong> <br> * <strong>[13.6.4] The <code>for-in</code> and <code>for-of</code> Statements</strong> * * <pre> * IterationStatement<sub>[Yield, Return]</sub> : * for ( Expression<sub>[?Yield]opt</sub> ; Expression<sub>[In, ?Yield]opt</sub> ; Expression<sub>[In, ?Yield]opt</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( var VariableDeclarationList<sub>[?Yield]</sub> ; Expression<sub>[In, ?Yield]opt</sub> ; Expression<sub>[In, ?Yield]opt</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( LexicalDeclaration<sub>[?Yield]</sub> ; Expression<sub>[In, ?Yield]opt</sub> ; Expression<sub>[In, ?Yield]opt</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( LeftHandSideExpression<sub>[?Yield]</sub> in Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( var ForBinding<sub>[?Yield]</sub> in Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( ForDeclaration<sub>[?Yield]</sub> in Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( LeftHandSideExpression<sub>[?Yield]</sub> of AssignmentExpression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( var ForBinding<sub>[?Yield]</sub> of AssignmentExpression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * for ( ForDeclaration<sub>[?Yield]</sub> of AssignmentExpression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * ForDeclaration<sub>[Yield]</sub> : * LetOrConst ForBinding<sub>[?Yield]</sub> * ForBinding<sub>[Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> * BindingPattern<sub>[?Yield]</sub> * </pre> */ private IterationStatement forStatement(Set<String> labelSet) { long begin = ts.beginPosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each") && isEnabled(CompatibilityOption.ForEachStatement)) { consume("each"); each = true; } consume(Token.LP); BlockContext lexBlockContext = null; Node head; switch (token()) { case VAR: long beginVar = ts.beginPosition(); consume(Token.VAR); List<VariableDeclaration> decls = variableDeclarationList(false); VariableStatement varStmt = new VariableStatement(beginVar, ts.endPosition(), decls); addVarScopedDeclaration(varStmt); head = varStmt; break; case SEMI: head = null; break; case CONST: lexBlockContext = enterBlockContext(); head = lexicalDeclaration(false); break; case LET: if (lexicalBindingFirstSet(peek())) { lexBlockContext = enterBlockContext(); head = lexicalDeclaration(false); break; } // 'let' as identifier, e.g. `for (let ;;) {}` // fall-through default: head = expression(false); break; } if (!each && token() == Token.SEMI) { head = validateFor(head); consume(Token.SEMI); Expression test = null; if (token() != Token.SEMI) { test = expression(true); } consume(Token.SEMI); Expression step = null; if (token() != Token.RP) { step = expression(true); } consume(Token.RP); LabelContext labelCx = enterIteration(begin, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForStatement iteration = new ForStatement(begin, ts.endPosition(), lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, test, step, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else if (each || token() == Token.IN) { head = validateForInOf(head); consume(Token.IN); Expression expr; if (lexBlockContext == null) { expr = expression(true); } else { exitBlockContext(); expr = expression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(begin, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } if (each) { ForEachStatement iteration = new ForEachStatement(begin, ts.endPosition(), lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else { ForInStatement iteration = new ForInStatement(begin, ts.endPosition(), lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } else { head = validateForInOf(head); consume("of"); Expression expr; if (lexBlockContext == null) { expr = assignmentExpression(true); } else { exitBlockContext(); expr = assignmentExpression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(begin, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForOfStatement iteration = new ForOfStatement(begin, ts.endPosition(), lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } /** * @see #forStatement(Set) */ private Node validateFor(Node head) { if (head instanceof VariableStatement) { for (VariableDeclaration decl : ((VariableStatement) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } } } else if (head instanceof LexicalDeclaration) { boolean isConst = ((LexicalDeclaration) head).getType() == LexicalDeclaration.Type.Const; for (LexicalBinding decl : ((LexicalDeclaration) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } if (isConst && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.ConstMissingInitialiser); } } } return head; } /** * @see #forStatement(Set) */ private Node validateForInOf(Node head) { if (head instanceof VariableStatement) { // expected: single variable declaration with no initialiser List<VariableDeclaration> elements = ((VariableStatement) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof LexicalDeclaration) { // expected: single lexical binding with no initialiser List<LexicalBinding> elements = ((LexicalDeclaration) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof Expression) { // expected: left-hand side expression return validateAssignment((Expression) head, ExceptionType.SyntaxError, Messages.Key.InvalidAssignmentTarget); } throw reportSyntaxError(head, Messages.Key.InvalidForInOfHead); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateSimpleAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { if (lhs instanceof Identifier) { if (context.strictMode != StrictMode.NonStrict) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportStrictModeSyntaxError(lhs, Messages.Key.StrictModeInvalidAssignmentTarget); } } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getType() == SuperExpression.Type.ElementAccessor || superExpr.getType() == SuperExpression.Type.PropertyAccessor) { return superExpr; } } // everything else => invalid lhs throw reportError(type, lhs.getBeginPosition(), messageKey); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { // rewrite object/array literal to destructuring form if (lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } return validateSimpleAssignment(lhs, type, messageKey); } private ObjectAssignmentPattern toDestructuring(ObjectLiteral object) { List<AssignmentProperty> list = newSmallList(); for (PropertyDefinition p : object.getProperties()) { AssignmentProperty property; if (p instanceof PropertyValueDefinition) { // AssignmentProperty : PropertyName ':' AssignmentElement // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression PropertyValueDefinition def = (PropertyValueDefinition) p; PropertyName propertyName = def.getPropertyName(); Expression propertyValue = def.getPropertyValue(); LeftHandSideExpression target; Expression initialiser; if (propertyValue instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) propertyValue; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(p, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(propertyValue); initialiser = null; } property = new AssignmentProperty(p.getBeginPosition(), p.getEndPosition(), propertyName, target, initialiser); } else if (p instanceof PropertyNameDefinition) { // AssignmentProperty : Identifier PropertyNameDefinition def = (PropertyNameDefinition) p; assignmentProperty_EarlyErrors(def.getPropertyName()); property = new AssignmentProperty(p.getBeginPosition(), p.getEndPosition(), def.getPropertyName(), null); } else if (p instanceof CoverInitialisedName) { // AssignmentProperty : Identifier Initialiser CoverInitialisedName def = (CoverInitialisedName) p; assignmentProperty_EarlyErrors(def.getPropertyName()); property = new AssignmentProperty(p.getBeginPosition(), p.getEndPosition(), def.getPropertyName(), def.getInitialiser()); } else { assert p instanceof MethodDefinition; throw reportSyntaxError(p, Messages.Key.InvalidDestructuring); } list.add(property); } context.removeLiteral(object); ObjectAssignmentPattern pattern = new ObjectAssignmentPattern(object.getBeginPosition(), object.getEndPosition(), list); if (object.isParenthesised()) { pattern.addParentheses(); } return pattern; } private ArrayAssignmentPattern toDestructuring(ArrayLiteral array) { List<AssignmentElementItem> list = newSmallList(); for (Iterator<Expression> iterator = array.getElements().iterator(); iterator.hasNext();) { Expression e = iterator.next(); AssignmentElementItem element; if (e instanceof Elision) { // Elision element = (Elision) e; } else if (e instanceof SpreadElement) { // AssignmentRestElement : ... DestructuringAssignmentTarget // DestructuringAssignmentTarget : LeftHandSideExpression Expression expression = ((SpreadElement) e).getExpression(); LeftHandSideExpression target = destructuringSimpleAssignmentTarget(expression); element = new AssignmentRestElement(e.getBeginPosition(), e.getEndPosition(), target); // no further elements after AssignmentRestElement allowed if (iterator.hasNext()) { reportSyntaxError(iterator.next(), Messages.Key.InvalidDestructuring); } } else { // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression LeftHandSideExpression target; Expression initialiser; if (e instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) e; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(e, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(e); initialiser = null; } element = new AssignmentElement(e.getBeginPosition(), e.getEndPosition(), target, initialiser); } list.add(element); } ArrayAssignmentPattern pattern = new ArrayAssignmentPattern(array.getBeginPosition(), array.getEndPosition(), list); if (array.isParenthesised()) { pattern.addParentheses(); } return pattern; } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, true); } private LeftHandSideExpression destructuringSimpleAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, false); } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs, boolean extended) { if (lhs instanceof Identifier) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportSyntaxError(lhs, Messages.Key.InvalidAssignmentTarget); } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (extended && lhs instanceof ObjectAssignmentPattern) { return (ObjectAssignmentPattern) lhs; } else if (extended && lhs instanceof ArrayAssignmentPattern) { return (ArrayAssignmentPattern) lhs; } else if (extended && lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (extended && lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getType() == SuperExpression.Type.ElementAccessor || superExpr.getType() == SuperExpression.Type.PropertyAccessor) { return superExpr; } } // everything else => invalid lhs throw reportSyntaxError(lhs, Messages.Key.InvalidDestructuring); } private void assignmentProperty_EarlyErrors(Identifier identifier) { switch (identifier.getName()) { case "eval": case "arguments": case "this": case "super": reportSyntaxError(identifier, Messages.Key.InvalidDestructuring); } } /** * <strong>[13.7] The <code>continue</code> Statement</strong> * * <pre> * ContinueStatement : * continue ; * continue [no <i>LineTerminator</i> here] NonResolvedIdentifier ; * </pre> */ private ContinueStatement continueStatement() { long begin = ts.beginPosition(); String label; consume(Token.CONTINUE); if (noLineTerminator() && isNonResolvedIdentifier(token())) { label = nonResolvedIdentifier(); } else { label = null; } semicolon(); LabelContext target = findContinueTarget(label); if (target == null) { if (label == null) { reportSyntaxError(begin, Messages.Key.InvalidContinueTarget); } else { reportSyntaxError(begin, Messages.Key.LabelTargetNotFound, label); } } if (target.type != StatementType.Iteration) { reportSyntaxError(begin, Messages.Key.InvalidContinueTarget); } target.mark(Abrupt.Continue); return new ContinueStatement(begin, ts.endPosition(), label); } /** * <strong>[13.8] The <code>break</code> Statement</strong> * * <pre> * BreakStatement : * break ; * break [no <i>LineTerminator</i> here] NonResolvedIdentifier ; * </pre> */ private BreakStatement breakStatement() { long begin = ts.beginPosition(); String label; consume(Token.BREAK); if (noLineTerminator() && isNonResolvedIdentifier(token())) { label = nonResolvedIdentifier(); } else { label = null; } semicolon(); LabelContext target = findBreakTarget(label); if (target == null) { if (label == null) { reportSyntaxError(begin, Messages.Key.InvalidBreakTarget); } else { reportSyntaxError(begin, Messages.Key.LabelTargetNotFound, label); } } target.mark(Abrupt.Break); return new BreakStatement(begin, ts.endPosition(), label); } /** * <strong>[13.9] The <code>return</code> Statement</strong> * * <pre> * ReturnStatement<sub>[Yield]</sub> : * return ; * return [no <i>LineTerminator</i> here] Expression<sub>[In, ?Yield]</sub> ; * </pre> */ private ReturnStatement returnStatement() { if (!context.returnAllowed) { reportSyntaxError(Messages.Key.InvalidReturnStatement); } long begin = ts.beginPosition(); Expression expr = null; consume(Token.RETURN); if (noLineTerminator() && !(token() == Token.SEMI || token() == Token.RC || token() == Token.EOF)) { expr = expression(true); } semicolon(); return new ReturnStatement(begin, ts.endPosition(), expr); } /** * <strong>[13.10] The <code>with</code> Statement</strong> * * <pre> * WithStatement<sub>[Yield, Return]</sub> : * with ( Expression<sub>[In, ?Yield]</sub> ) Statement<sub>[?Yield, ?Return]</sub> * </pre> */ private WithStatement withStatement() { long begin = ts.beginPosition(); reportStrictModeSyntaxError(begin, Messages.Key.StrictModeWithStatement); consume(Token.WITH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); BlockContext scope = enterWithContext(); Statement stmt = statement(); exitWithContext(); WithStatement withStatement = new WithStatement(begin, ts.endPosition(), scope, expr, stmt); scope.node = withStatement; return withStatement; } /** * <strong>[13.11] The <code>switch</code> Statement</strong> * * <pre> * SwitchStatement<sub>[Yield, Return]</sub> : * switch ( Expression<sub>[In, ?Yield]</sub> ) CaseBlock<sub>[?Yield, ?Return]</sub> * CaseBlock<sub>[Yield, Return]</sub> : * { CaseClauses<sub>[?Yield, ?Return]opt</sub> } * { CaseClauses<sub>[?Yield, ?Return]opt</sub> DefaultClause<sub>[?Yield, ?Return]</sub> CaseClauses<sub>[?Yield, ?Return]opt</sub> } * CaseClauses<sub>[Yield, Return]</sub> : * CaseClause<sub>[?Yield, ?Return]</sub> * CaseClauses<sub>[?Yield, ?Return]</sub> CaseClause<sub>[?Yield, ?Return]</sub> * CaseClause<sub>[Yield, Return]</sub> : * case Expression<sub>[In, ?Yield]</sub> : StatementList<sub>[?Yield, ?Return]opt</sub> * DefaultClause : * default : StatementList<sub>[?Yield, ?Return]opt</sub> * </pre> */ private SwitchStatement switchStatement(Set<String> labelSet) { List<SwitchClause> clauses = newList(); long begin = ts.beginPosition(); consume(Token.SWITCH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); consume(Token.LC); LabelContext labelCx = enterBreakable(begin, labelSet); BlockContext scope = enterBlockContext(); boolean hasDefault = false; for (;;) { long beginClause = ts.beginPosition(); Expression caseExpr; Token tok = token(); if (tok == Token.CASE) { consume(Token.CASE); caseExpr = expression(true); consume(Token.COLON); } else if (tok == Token.DEFAULT && !hasDefault) { hasDefault = true; consume(Token.DEFAULT); consume(Token.COLON); caseExpr = null; } else { break; } List<StatementListItem> list = newList(); statementlist: for (;;) { switch (token()) { case CASE: case DEFAULT: case RC: break statementlist; default: list.add(statementListItem()); } } clauses.add(new SwitchClause(beginClause, ts.endPosition(), caseExpr, list)); } exitBlockContext(); exitBreakable(); consume(Token.RC); SwitchStatement switchStatement = new SwitchStatement(begin, ts.endPosition(), scope, labelCx.abrupts, labelCx.labelSet, expr, clauses); scope.node = switchStatement; return switchStatement; } /** * <strong>[13.12] Labelled Statements</strong> * * <pre> * LabelledStatement<sub>[Yield, Return]</sub> : * NonResolvedIdentifier : Statement<sub>[?Yield, ?Return]</sub> * </pre> */ private Statement labelledStatement() { long begin = ts.beginPosition(); LinkedHashSet<String> labelSet = new LinkedHashSet<>(4); labels: for (;;) { switch (token()) { case FOR: return forStatement(labelSet); case WHILE: return whileStatement(labelSet); case DO: return doWhileStatement(labelSet); case SWITCH: return switchStatement(labelSet); case LET: if (isEnabled(CompatibilityOption.LetStatement) || isEnabled(CompatibilityOption.LetExpression)) { break labels; } // fall-through case YIELD: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case NAME: if (LOOKAHEAD(Token.COLON)) { break; } case LC: case VAR: case SEMI: case IF: case CONTINUE: case BREAK: case RETURN: case WITH: case THROW: case TRY: case DEBUGGER: default: break labels; } long beginLabel = ts.beginPosition(); String name = nonResolvedIdentifier(); consume(Token.COLON); if (!labelSet.add(name)) { reportSyntaxError(beginLabel, Messages.Key.DuplicateLabel, name); } } assert !labelSet.isEmpty(); LabelContext labelCx = enterLabelled(begin, StatementType.Statement, labelSet); Statement stmt = statement(); exitLabelled(); return new LabelledStatement(begin, ts.endPosition(), labelCx.abrupts, labelCx.labelSet, stmt); } /** * <strong>[13.13] The <code>throw</code> Statement</strong> * * <pre> * ThrowStatement<sub>[Yield]</sub> : * throw [no <i>LineTerminator</i> here] Expression<sub>[In, ?Yield]</sub> ; * </pre> */ private ThrowStatement throwStatement() { long begin = ts.beginPosition(); consume(Token.THROW); if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } Expression expr = expression(true); semicolon(); return new ThrowStatement(begin, ts.endPosition(), expr); } /** * <strong>[13.14] The <code>try</code> Statement</strong> * * <pre> * TryStatement<sub>[Yield, Return]</sub> : * try Block<sub>[?Yield, ?Return]</sub> Catch<sub>[?Yield, ?Return]</sub> * try Block<sub>[?Yield, ?Return]</sub> Finally<sub>[?Yield, ?Return]</sub> * try Block<sub>[?Yield, ?Return]</sub> Catch<sub>[?Yield, ?Return]</sub> Finally<sub>[?Yield, ?Return]</sub> * Catch<sub>[Yield, Return]</sub> : * catch ( CatchParameter<sub>[?Yield]</sub> ) Block<sub>[?Yield, ?Return]</sub> * Finally<sub>[Yield, Return]</sub> : * finally Block<sub>[?Yield, ?Return]</sub> * CatchParameter<sub>[Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> * BindingPattern<sub>[?Yield]</sub> * </pre> */ private TryStatement tryStatement() { BlockStatement tryBlock, finallyBlock = null; CatchNode catchNode = null; List<GuardedCatchNode> guardedCatchNodes = emptyList(); long begin = ts.beginPosition(); consume(Token.TRY); tryBlock = block(NO_INHERITED_BINDING); Token tok = token(); if (tok == Token.CATCH) { if (isEnabled(CompatibilityOption.GuardedCatch)) { guardedCatchNodes = newSmallList(); while (token() == Token.CATCH && catchNode == null) { long beginCatch = ts.beginPosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); Expression guard; if (token() == Token.IF) { consume(Token.IF); guard = expression(true); } else { guard = null; } consume(Token.RP); // CatchBlock receives a list of non-available lexical declarable names to // fulfill the early error restriction that the BoundNames of CatchParameter // must not also occur in either the LexicallyDeclaredNames or the // VarDeclaredNames of CatchBlock BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); if (guard != null) { GuardedCatchNode guardedCatchNode = new GuardedCatchNode(beginCatch, ts.endPosition(), catchScope, catchParameter, guard, catchBlock); catchScope.node = guardedCatchNode; guardedCatchNodes.add(guardedCatchNode); } else { catchNode = new CatchNode(beginCatch, ts.endPosition(), catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } } } else { long beginCatch = ts.beginPosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); consume(Token.RP); // CatchBlock receives a list of non-available lexical declarable names to // fulfill the early error restriction that the BoundNames of CatchParameter // must not also occur in either the LexicallyDeclaredNames or the // VarDeclaredNames of CatchBlock BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); catchNode = new CatchNode(beginCatch, ts.endPosition(), catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } if (token() == Token.FINALLY) { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } } else { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } return new TryStatement(begin, ts.endPosition(), tryBlock, catchNode, guardedCatchNodes, finallyBlock); } /** * <strong>[13.15] The <code>debugger</code> Statement</strong> * * <pre> * DebuggerStatement : * debugger ; * </pre> */ private DebuggerStatement debuggerStatement() { long begin = ts.beginPosition(); consume(Token.DEBUGGER); semicolon(); return new DebuggerStatement(begin, ts.endPosition()); } /** * <strong>[Extension] The <code>let</code> Statement</strong> * * <pre> * LetStatement<sub>[Yield, Return]</sub> : * let ( BindingList<sub>[In, ?Yield]</sub> ) BlockStatement<sub>[?Yield, ?Return]</sub> * </pre> */ private Statement letStatement() { BlockContext scope = enterBlockContext(); long begin = ts.beginPosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); if (token() != Token.LC && isEnabled(CompatibilityOption.LetExpression)) { // let expression disguised as let statement - also error in strict mode(!) reportStrictModeSyntaxError(begin, Messages.Key.UnexpectedToken, token().toString()); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(begin, ts.endPosition(), scope, bindings, expression); scope.node = letExpression; return new ExpressionStatement(begin, ts.endPosition(), letExpression); } else { BlockStatement letBlock = block(toBindings(bindings)); exitBlockContext(); LetStatement block = new LetStatement(begin, ts.endPosition(), scope, bindings, letBlock); scope.node = block; return block; } } private List<Binding> toBindings(List<LexicalBinding> lexicalBindings) { ArrayList<Binding> bindings = new ArrayList<>(lexicalBindings.size()); for (LexicalBinding lexicalBinding : lexicalBindings) { bindings.add(lexicalBinding.getBinding()); } return bindings; } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * PrimaryExpresion<sub>[Yield]</sub> : * this * IdentifierReference<sub>[?Yield]</sub> * Literal * ArrayInitialiser<sub>[?Yield]</sub> * ObjectLiteral<sub>[?Yield]</sub> * FunctionExpression * ClassExpression * GeneratorExpression * GeneratorComprehension<sub>[?Yield]</sub> * RegularExpressionLiteral * TemplateLiteral<sub>[?Yield]</sub> * CoverParenthesisedExpressionAndArrowParameterList<sub>[?Yield]</sub> * Literal : * NullLiteral * ValueLiteral * ValueLiteral : * BooleanLiteral * NumericLiteral * StringLiteral * </pre> */ private Expression primaryExpression() { long begin = ts.beginPosition(); Token tok = token(); switch (tok) { case THIS: consume(tok); return new ThisExpression(begin, ts.endPosition()); case NULL: consume(tok); return new NullLiteral(begin, ts.endPosition()); case FALSE: case TRUE: consume(tok); return new BooleanLiteral(begin, ts.endPosition(), tok == Token.TRUE); case NUMBER: double number = numericLiteral(); return new NumericLiteral(begin, ts.endPosition(), number); case STRING: String string = stringLiteral(); return new StringLiteral(begin, ts.endPosition(), string); case DIV: case ASSIGN_DIV: return regularExpressionLiteral(tok); case LB: return arrayInitialiser(); case LC: return objectLiteral(); case FUNCTION: return functionOrGeneratorExpression(); case CLASS: return classExpression(); case LP: if (LOOKAHEAD(Token.FOR)) { return generatorComprehension(); } else { return coverParenthesisedExpressionAndArrowParameterList(); } case TEMPLATE: return templateLiteral(false); case LET: if (isEnabled(CompatibilityOption.LetExpression)) { return letExpression(); } case YIELD: if (context.noDivAfterYield && LOOKAHEAD(Token.DIV)) { consume(Token.YIELD); reportTokenMismatch(Token.DIV, Token.REGEXP); } default: String ident = identifierReference(); return new Identifier(begin, ts.endPosition(), ident); } } private Expression functionOrGeneratorExpression() { if (LOOKAHEAD(Token.MUL)) { return generatorExpression(false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionExpression(); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorExpression(true); } } } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * CoverParenthesisedExpressionAndArrowParameterList<sub>[Yield]</sub> : * ( Expression<sub>[In, ?Yield]</sub> ) * ( ) * ( ... BindingIdentifier<sub>[?Yield]</sub> ) * ( Expression<sub>[In, ?Yield]</sub> , ... BindingIdentifier<sub>[?Yield]</sub>) * </pre> */ private Expression coverParenthesisedExpressionAndArrowParameterList() { long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); Expression expr; if (token() == Token.RP) { expr = arrowFunctionEmptyParameters(); } else if (token() == Token.TRIPLE_DOT) { expr = arrowFunctionRestParameter(); } else { // inlined `expression(true)` expr = assignmentExpressionNoValidation(true); if (token() == Token.FOR && isEnabled(CompatibilityOption.LegacyComprehension)) { ts.reset(position, lineinfo); return legacyGeneratorComprehension(); } if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); if (token() == Token.TRIPLE_DOT) { list.add(arrowFunctionRestParameter()); break; } expr = assignmentExpression(true); list.add(expr); } expr = new CommaExpression(list); } } expr.addParentheses(); consume(Token.RP); return expr; } private EmptyExpression arrowFunctionEmptyParameters() { if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(Messages.Key.EmptyParenthesisedExpression); } return new EmptyExpression(0, 0); } private SpreadElement arrowFunctionRestParameter() { long begin = ts.beginPosition(); consume(Token.TRIPLE_DOT); String ident = identifierReference(); // actually bindingIdentifier() Identifier identifier = new Identifier(ts.beginPosition(), ts.endPosition(), ident); SpreadElement spread = new SpreadElement(begin, ts.endPosition(), identifier); if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(spread, Messages.Key.InvalidSpreadExpression); } return spread; } /** * <strong>[12.1.2] Identifier Reference</strong> * * <pre> * NonResolvedIdentifier<sub>[Yield]</sub> : * Identifier * <sub>[~Yield]</sub> yield * </pre> */ private String nonResolvedIdentifier() { Token tok = token(); if (!isNonResolvedIdentifier(tok)) { reportTokenNotIdentifier(tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[12.1.2] Identifier Reference</strong> * * <pre> * IdentifierReference<sub>[Yield]</sub> : * NonResolvedIdentifier<sub>[?Yield]</sub> * * NonResolvedIdentifier<sub>[Yield]</sub> : * Identifier * <sub>[~Yield]</sub> yield * </pre> */ private String identifierReference() { Token tok = token(); if (!isIdentifierReference(tok)) { reportTokenNotIdentifier(tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[12.1.2] Identifier Reference</strong> * * <pre> * IdentifierReference<sub>[Yield]</sub> : * NonResolvedIdentifier<sub>[?Yield]</sub> * * NonResolvedIdentifier<sub>[Yield]</sub> : * Identifier * <sub>[~Yield]</sub> yield * </pre> */ private String strictIdentifierReference() { Token tok = token(); if (!isStrictIdentifierReference(tok)) { reportTokenNotIdentifier(tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[12.1.2] Identifier Reference</strong> */ private boolean isNonResolvedIdentifier(Token tok) { switch (tok) { case NAME: return true; case YIELD: case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: if (context.strictMode != StrictMode.NonStrict) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); } return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[12.1.2] Identifier Reference</strong> */ private boolean isIdentifierReference(Token tok) { switch (tok) { case NAME: return true; case YIELD: return isYieldName(); case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: if (context.strictMode != StrictMode.NonStrict) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); } return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[12.1.2] Identifier Reference</strong> */ private boolean isStrictIdentifierReference(Token tok) { switch (tok) { case NAME: return true; case YIELD: case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: throw reportSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); default: return false; } } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the current context */ private boolean isYieldName() { return isYieldName(context); } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the supplied context */ private boolean isYieldName(ParseContext context) { // 'yield' is always a keyword in strict-mode and in generators if (context.strictMode == StrictMode.Strict || context.kind == ContextKind.Generator) { return false; } // proactively flag as syntax error if current strict mode is unknown reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); return true; } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayInitialiser<sub>[Yield]</sub> : * ArrayLiteral<sub>[?Yield]</sub> * ArrayComprehension<sub>[?Yield]</sub> * </pre> */ private ArrayInitialiser arrayInitialiser() { if (LOOKAHEAD(Token.FOR)) { return arrayComprehension(); } else { long begin = ts.beginPosition(); if (isEnabled(CompatibilityOption.LegacyComprehension)) { switch (peek()) { case RB: case COMMA: case TRIPLE_DOT: break; default: // TODO: report eclipse formatter bug long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LB); Expression expression = assignmentExpressionNoValidation(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); return legacyArrayComprehension(); } return arrayLiteral(begin, expression); } } return arrayLiteral(begin, null); } } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayLiteral<sub>[Yield]</sub> : * [ Elision<sub>opt</sub> ] * [ ElementList<sub>[?Yield]</sub> ] * [ ElementList<sub>[?Yield]</sub> , Elision<sub>opt</sub> ] * ElementList<sub>[Yield]</sub> : * Elision<sub>opt</sub> AssignmentExpression<sub>[In, ?Yield]</sub> * Elision<sub>opt</sub> SpreadElement<sub>[?Yield]</sub> * ElementList<sub>[?Yield]</sub> , Elision<sub>opt</sub> AssignmentExpression<sub>[In, ?Yield]</sub> * ElementList<sub>[?Yield]</sub> , Elision<sub>opt</sub> SpreadElement<sub>[?Yield]</sub> * Elision : * , * Elision , * SpreadElement<sub>[Yield]</sub> : * ... AssignmentExpression<sub>[In, ?Yield]</sub> * </pre> */ private ArrayLiteral arrayLiteral(long begin, Expression expr) { List<Expression> list = newList(); boolean needComma = false; if (expr == null) { consume(Token.LB); } else { list.add(expr); needComma = true; } for (Token tok; (tok = token()) != Token.RB;) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new Elision(0, 0)); } else if (tok == Token.TRIPLE_DOT) { long beginSpread = ts.beginPosition(); consume(Token.TRIPLE_DOT); Expression expression = assignmentExpression(true); list.add(new SpreadElement(beginSpread, ts.endPosition(), expression)); needComma = true; } else { list.add(assignmentExpressionNoValidation(true)); needComma = true; } } consume(Token.RB); return new ArrayLiteral(begin, ts.endPosition(), list); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ArrayComprehension<sub>[Yield]</sub> : * [ Comprehension<sub>[?Yield]</sub> ] * </pre> */ private ArrayComprehension arrayComprehension() { long begin = ts.beginPosition(); consume(Token.LB); Comprehension comprehension = comprehension(); consume(Token.RB); return new ArrayComprehension(begin, ts.endPosition(), comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * Comprehension<sub>[Yield]</sub> : * ComprehensionFor<sub>[?Yield]</sub> ComprehensionTail<sub>[?Yield]</sub> * ComprehensionTail<sub>[Yield]</sub> : * AssignmentExpression<sub>[In, ?Yield]</sub> * ComprehensionFor<sub>[?Yield]</sub> ComprehensionTail<sub>[?Yield]</sub> * ComprehensionIf<sub>[?Yield]</sub> ComprehensionTail<sub>[?Yield]</sub> * </pre> */ private Comprehension comprehension() { assert token() == Token.FOR; List<ComprehensionQualifier> list = newSmallList(); int scopes = 0; for (;;) { ComprehensionQualifier qualifier; if (token() == Token.FOR) { scopes += 1; qualifier = comprehensionFor(); } else if (token() == Token.IF) { qualifier = comprehensionIf(); } else { break; } list.add(qualifier); } Expression expression = assignmentExpression(true); while (scopes exitBlockContext(); } return new Comprehension(list, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionFor<sub>[Yield]</sub> : * for ( ForBinding<sub>[?Yield]</sub> of AssignmentExpression<sub>[In, ?Yield]</sub> ) * ForBinding<sub>[Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> * BindingPattern<sub>[?Yield]</sub> * </pre> */ private ComprehensionFor comprehensionFor() { long begin = ts.beginPosition(); consume(Token.FOR); consume(Token.LP); Binding b = forBinding(false); consume("of"); Expression expression = assignmentExpression(true); consume(Token.RP); BlockContext scope = enterBlockContext(b); return new ComprehensionFor(begin, ts.endPosition(), scope, b, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ForBinding<sub>[Yield]</sub> : * BindingIdentifier<sub>[?Yield]</sub> * BindingPattern<sub>[?Yield]</sub> * </pre> */ private Binding forBinding(boolean allowLet) { return binding(allowLet); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionIf<sub>[Yield]</sub> : * if ( AssignmentExpression<sub>[In, ?Yield]</sub> ) * </pre> */ private ComprehensionIf comprehensionIf() { long begin = ts.beginPosition(); consume(Token.IF); consume(Token.LP); Expression expression = assignmentExpression(true); consume(Token.RP); return new ComprehensionIf(begin, ts.endPosition(), expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyArrayComprehension<sub>[Yield]</sub> : * [ LegacyComprehension<sub>[?Yield]</sub> ] * </pre> */ private ArrayComprehension legacyArrayComprehension() { long begin = ts.beginPosition(); consume(Token.LB); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RB); return new ArrayComprehension(begin, ts.endPosition(), comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyComprehension<sub>[Yield]</sub> : * AssignmentExpression<sub>[In, ?Yield]</sub> LegacyComprehensionForList<sub>[?Yield]</sub> LegacyComprehensionIf<sub>[?Yield]opt</sub> * LegacyComprehensionForList<sub>[Yield]</sub> : * LegacyComprehensionFor<sub>[?Yield]</sub> LegacyComprehensionForList<sub>[?Yield]opt</sub> * LegacyComprehensionFor<sub>[Yield]</sub> : * for ( ForBinding<sub>[?Yield]</sub> of Expression<sub>[In, ?Yield]</sub> ) * for ( ForBinding<sub>[?Yield]</sub> in Expression<sub>[In, ?Yield]</sub> ) * for each ( ForBinding<sub>[?Yield]</sub> in Expression<sub>[In, ?Yield]</sub> ) * LegacyComprehensionIf<sub>[Yield]</sub> : * if ( Expression<sub>[In, ?Yield]</sub> ) * </pre> */ private LegacyComprehension legacyComprehension() { BlockContext scope = enterBlockContext(); Expression expr = assignmentExpression(true); assert token() == Token.FOR : "empty legacy comprehension"; List<ComprehensionQualifier> list = newSmallList(); while (token() == Token.FOR) { long begin = ts.beginPosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each")) { consume("each"); each = true; } consume(Token.LP); Binding b = forBinding(false); addLexDeclaredName(b); LegacyComprehensionFor.IterationKind iterationKind; if (each) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.EnumerateValues; } else if (token() == Token.IN) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.Enumerate; } else { consume("of"); iterationKind = LegacyComprehensionFor.IterationKind.Iterate; } Expression expression = expression(true); consume(Token.RP); list.add(new LegacyComprehensionFor(begin, ts.endPosition(), iterationKind, b, expression)); } if (token() == Token.IF) { long begin = ts.beginPosition(); consume(Token.IF); consume(Token.LP); Expression expression = expression(true); consume(Token.RP); list.add(new ComprehensionIf(begin, ts.endPosition(), expression)); } exitBlockContext(); return new LegacyComprehension(scope, list, expr); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ObjectLiteral<sub>[Yield]</sub> : * { } * { PropertyDefinitionList<sub>[?Yield]</sub> } * { PropertyDefinitionList<sub>[?Yield]</sub> , } * PropertyDefinitionList<sub>[Yield]</sub> : * PropertyDefinition<sub>[?Yield]</sub> * PropertyDefinitionList<sub>[?Yield]</sub> , PropertyDefinition<sub>[?Yield]</sub> * </pre> */ private ObjectLiteral objectLiteral() { long begin = ts.beginPosition(); List<PropertyDefinition> defs = newList(); consume(Token.LC); while (token() != Token.RC) { defs.add(propertyDefinition()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); ObjectLiteral object = new ObjectLiteral(begin, ts.endPosition(), defs); context.addLiteral(object); return object; } private void objectLiteral_StaticSemantics(int oldCount) { ArrayDeque<ObjectLiteral> literals = context.objectLiterals; for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) { objectLiteral_StaticSemantics(literals.pop()); } } /** * 12.1.5.1 Static Semantics: Early Errors */ private void objectLiteral_StaticSemantics(ObjectLiteral object) { final int VALUE = 0, GETTER = 1, SETTER = 2, SPECIAL = 4; Map<String, Integer> values = new HashMap<>(); for (PropertyDefinition def : object.getProperties()) { PropertyName propertyName = def.getPropertyName(); String key = propertyName.getName(); if (key == null) { assert propertyName instanceof ComputedPropertyName; continue; } final int kind; if (def instanceof PropertyValueDefinition) { kind = VALUE; } else if (def instanceof PropertyNameDefinition) { kind = SPECIAL; } else if (def instanceof MethodDefinition) { MethodDefinition.MethodType type = ((MethodDefinition) def).getType(); kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : SPECIAL; } else { assert def instanceof CoverInitialisedName; // Always throw a Syntax Error if this production is present throw reportSyntaxError(def, Messages.Key.MissingColonAfterPropertyId, key); } // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any // duplicate entries [...] if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE && prev != VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == VALUE && prev == VALUE) { reportStrictModeSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SPECIAL) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyDefinition<sub>[Yield]</sub> : * IdentifierReference<sub>[?Yield]</sub> * CoverInitialisedName<sub>[?Yield]</sub> * PropertyName<sub>[?Yield]</sub> : AssignmentExpression<sub>[In, ?Yield]</sub> * MethodDefinition<sub>[?Yield]</sub> * CoverInitialisedName<sub>[Yield]</sub> : * IdentifierName Initialiser<sub>[In, ?Yield]</sub> * Initialiser<sub>[In, Yield]</sub> : * = AssignmentExpression<sub>[?In, ?Yield]</sub> * </pre> */ private PropertyDefinition propertyDefinition() { long begin = ts.beginPosition(); if (token() == Token.LB) { // either `PropertyName : AssignmentExpression` or MethodDefinition (normal) PropertyName propertyName = computedPropertyName(); if (token() == Token.COLON) { // it's the `PropertyName : AssignmentExpression` case consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(begin, ts.endPosition(), propertyName, propertyValue); } // otherwise it's MethodDefinition (normal) return normalMethod(begin, propertyName, false); } if (LOOKAHEAD(Token.COLON)) { PropertyName propertyName = literalPropertyName(); consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(begin, ts.endPosition(), propertyName, propertyValue); } if (LOOKAHEAD(Token.COMMA) || LOOKAHEAD(Token.RC)) { String ident = identifierReference(); Identifier identifier = new Identifier(begin, ts.endPosition(), ident); return new PropertyNameDefinition(begin, ts.endPosition(), identifier); } if (LOOKAHEAD(Token.ASSIGN)) { String ident = identifierReference(); Identifier identifier = new Identifier(begin, ts.endPosition(), ident); consume(Token.ASSIGN); Expression initialiser = assignmentExpression(true); return new CoverInitialisedName(begin, ts.endPosition(), identifier, initialiser); } return methodDefinition(false); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyName<sub>[Yield, GeneratorParameter]</sub> : * LiteralPropertyName * <sub>[+GeneratorParameter]</sub>ComputedPropertyName * <sub>[~GeneratorParameter]</sub>ComputedPropertyName<sub>[?Yield]</sub> * </pre> */ private PropertyName propertyName() { if (token() != Token.LB) { return literalPropertyName(); } else { return computedPropertyName(); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * LiteralPropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private PropertyName literalPropertyName() { long begin = ts.beginPosition(); switch (token()) { case STRING: String string = stringLiteral(); return new StringLiteral(begin, ts.endPosition(), string); case NUMBER: double number = numericLiteral(); return new NumericLiteral(begin, ts.endPosition(), number); default: String ident = identifierName(); return new Identifier(begin, ts.endPosition(), ident); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ComputedPropertyName<sub>[Yield]</sub> : * [ AssignmentExpression<sub>[In, ?Yield]</sub> ] * </pre> */ private PropertyName computedPropertyName() { long begin = ts.beginPosition(); consume(Token.LB); Expression expression = assignmentExpression(true); consume(Token.RB); return new ComputedPropertyName(begin, ts.endPosition(), expression); } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * GeneratorComprehension<sub>[Yield]</sub> : * ( Comprehension<sub>[?Yield]</sub> ) * </pre> */ private GeneratorComprehension generatorComprehension() { boolean yieldAllowed = context.yieldAllowed; newContext(ContextKind.GeneratorComprehension); try { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); // propagate the outer context's 'yield' state context.yieldAllowed = yieldAllowed; long begin = ts.beginPosition(); consume(Token.LP); Comprehension comprehension = comprehension(); consume(Token.RP); FunctionContext scope = context.funContext; GeneratorComprehension generator = new GeneratorComprehension(begin, ts.endPosition(), scope, comprehension); scope.node = generator; return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * LegacyGeneratorComprehension<sub>[Yield]</sub> : * ( LegacyComprehension<sub>[?Yield]</sub> ) * </pre> */ private GeneratorComprehension legacyGeneratorComprehension() { boolean yieldAllowed = context.yieldAllowed; newContext(ContextKind.GeneratorComprehension); try { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); // propagate the outer context's 'yield' state context.yieldAllowed = yieldAllowed; long begin = ts.beginPosition(); consume(Token.LP); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RP); FunctionContext scope = context.funContext; GeneratorComprehension generator = new GeneratorComprehension(begin, ts.endPosition(), scope, comprehension); scope.node = generator; return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[12.1.8] Regular Expression Literals</strong> * * <pre> * RegularExpressionLiteral :: * / RegularExpressionBody / RegularExpressionFlags * </pre> */ private Expression regularExpressionLiteral(Token tok) { long begin = ts.beginPosition(); String[] re = ts.readRegularExpression(tok); regularExpressionLiteral_EarlyErrors(begin, re[0], re[1]); consume(tok); return new RegularExpressionLiteral(begin, ts.endPosition(), re[0], re[1]); } /** * 12.1.8.1 Static Semantics: Early Errors */ private void regularExpressionLiteral_EarlyErrors(long sourcePos, String p, String f) { // parse to validate regular expression, but ignore actual result RegExpParser.parse(p, f, sourceFile, toLine(sourcePos), toColumn(sourcePos)); } /** * <strong>[12.1.9] Template Literals</strong> * * <pre> * TemplateLiteral<sub>[Yield]</sub> : * NoSubstitutionTemplate * TemplateHead Expression<sub>[In, ?Yield]</sub> [Lexical goal <i>InputElementTemplateTail</i>] TemplateSpans<sub>[?Yield]</sub> * TemplateSpans<sub>[Yield]</sub> : * TemplateTail * TemplateMiddleList<sub>[?Yield]</sub> [Lexical goal <i>InputElementTemplateTail</i>] TemplateTail * TemplateMiddleList<sub>[Yield]</sub> : * TemplateMiddle Expression<sub>[In, ?Yield]</sub> * TemplateMiddleList<sub>[?Yield]</sub> [Lexical goal <i>InputElementTemplateTail</i>] TemplateMiddle Expression<sub>[In, ?Yield]</sub> * </pre> */ private TemplateLiteral templateLiteral(boolean tagged) { List<Expression> elements = newList(); long begin = ts.beginPosition(); templateCharacters(elements, Token.TEMPLATE); while (token() == Token.LC) { consume(Token.LC); elements.add(expression(true)); templateCharacters(elements, Token.RC); } consume(Token.TEMPLATE); if ((elements.size() / 2) + 1 > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } return new TemplateLiteral(begin, ts.endPosition(), tagged, elements); } private void templateCharacters(List<Expression> elements, Token start) { long begin = ts.beginPosition(); String[] values = ts.readTemplateLiteral(start); elements.add(new TemplateCharacters(begin, ts.endPosition(), values[0], values[1])); } /** * <strong>[Extension] The <code>let</code> Expression</strong> * * <pre> * LetExpression<sub>[Yield]</sub> : * let ( BindingList<sub>[In, ?Yield]</sub> ) AssignmentExpression<sub>[In, ?Yield]</sub> * </pre> */ private LetExpression letExpression() { BlockContext scope = enterBlockContext(); long begin = ts.beginPosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(begin, ts.endPosition(), scope, bindings, expression); scope.node = letExpression; return letExpression; } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * MemberExpression<sub>[Yield]</sub> : * [Lexical goal <i>InputElementRegExp</i>] PrimaryExpression<sub>[?Yield]</sub> * MemberExpression<sub>[?Yield]</sub> [ Expression<sub>[In, ?Yield]</sub> ] * MemberExpression<sub>[?Yield]</sub> . IdentifierName * MemberExpression<sub>[?Yield]</sub> TemplateLiteral<sub>[?Yield]</sub> * super [ Expression<sub>[In, ?Yield]</sub> ] * super . IdentifierName * new super Arguments<sub>[?Yield]opt</sub> * new MemberExpression<sub>[?Yield]</sub> Arguments<sub>[?Yield]</sub> * NewExpression<sub>[Yield]</sub> : * MemberExpression<sub>[?Yield]</sub> * new NewExpression<sub>[?Yield]</sub> * CallExpression<sub>[Yield]</sub> : * MemberExpression<sub>[?Yield]</sub> Arguments<sub>[?Yield]</sub> * super Arguments<sub>[?Yield]</sub> * CallExpression<sub>[?Yield]</sub> Arguments<sub>[?Yield]</sub> * CallExpression<sub>[?Yield]</sub> [ Expression<sub>[In, ?Yield]</sub> ] * CallExpression<sub>[?Yield]</sub> . IdentifierName * CallExpression<sub>[?Yield]</sub> TemplateLiteral<sub>[?Yield]</sub> * LeftHandSideExpression<sub>[Yield]</sub> : * NewExpression<sub>[?Yield]</sub> * CallExpression<sub>[?Yield]</sub> * </pre> */ private Expression leftHandSideExpression(boolean allowCall) { long begin = ts.beginPosition(); Expression lhs; if (token() == Token.NEW) { consume(Token.NEW); Expression expr = leftHandSideExpression(false); List<Expression> args = null; if (token() == Token.LP) { args = arguments(); } else { args = emptyList(); } lhs = new NewExpression(begin, ts.endPosition(), expr, args); } else if (token() == Token.SUPER) { ParseContext cx = context.findSuperContext(); if (cx.kind == ContextKind.Script && !isEnabled(Option.FunctionCode) || cx.kind == ContextKind.Module) { reportSyntaxError(Messages.Key.InvalidSuperExpression); } cx.setReferencesSuper(); consume(Token.SUPER); switch (token()) { case DOT: consume(Token.DOT); String name = identifierName(); lhs = new SuperExpression(begin, ts.endPosition(), name); break; case LB: consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new SuperExpression(begin, ts.endPosition(), expr); break; case LP: if (allowCall) { List<Expression> args = arguments(); lhs = new SuperExpression(begin, ts.endPosition(), args); break; } // fall-through case TEMPLATE: default: if (!allowCall) { return new SuperExpression(begin, ts.endPosition()); } throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } else { lhs = primaryExpression(); } for (;;) { switch (token()) { case DOT: begin = ts.beginPosition(); consume(Token.DOT); String name = identifierName(); lhs = new PropertyAccessor(begin, ts.endPosition(), lhs, name); break; case LB: begin = ts.beginPosition(); consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new ElementAccessor(begin, ts.endPosition(), lhs, expr); break; case LP: if (!allowCall) { return lhs; } if (lhs instanceof Identifier && "eval".equals(((Identifier) lhs).getName())) { context.topContext.directEval = true; } begin = ts.beginPosition(); List<Expression> args = arguments(); lhs = new CallExpression(begin, ts.endPosition(), lhs, args); break; case TEMPLATE: begin = ts.beginPosition(); TemplateLiteral templ = templateLiteral(true); lhs = new TemplateCallExpression(begin, ts.endPosition(), lhs, templ); break; default: return lhs; } } } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * Arguments<sub>[Yield]</sub> : * () * ( ArgumentList<sub>[?Yield]</sub> ) * ArgumentList<sub>[Yield]</sub> : * AssignmentExpression<sub>[In, ?Yield]</sub> * ... AssignmentExpression<sub>[In, ?Yield]</sub> * ArgumentList<sub>[?Yield]</sub> , AssignmentExpression<sub>[In, ?Yield]</sub> * ArgumentList<sub>[?Yield]</sub> , ... AssignmentExpression<sub>[In, ?Yield]</sub> * </pre> */ private List<Expression> arguments() { List<Expression> args = newSmallList(); long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); if (token() != Token.RP) { if (token() != Token.TRIPLE_DOT && isEnabled(CompatibilityOption.LegacyComprehension)) { Expression expr = assignmentExpression(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); args.add(legacyGeneratorComprehension()); return args; } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { consume(Token.RP); return args; } } for (;;) { Expression expr; if (token() == Token.TRIPLE_DOT) { long begin = ts.beginPosition(); consume(Token.TRIPLE_DOT); Expression e = assignmentExpression(true); expr = new CallSpreadElement(begin, ts.endPosition(), e); } else { expr = assignmentExpression(true); } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } if (args.size() > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } } consume(Token.RP); return args; } /** * <strong>[12.3] Postfix Expressions</strong><br> * <strong>[12.4] Unary Operators</strong> * * <pre> * PostfixExpression<sub>[Yield]</sub> : * LeftHandSideExpression<sub>[?Yield]</sub> * LeftHandSideExpression<sub>[?Yield]</sub> [no <i>LineTerminator</i> here] ++ * LeftHandSideExpression<sub>[?Yield]</sub> [no <i>LineTerminator</i> here] -- * UnaryExpression<sub>[Yield]</sub> : * PostfixExpression<sub>[?Yield]</sub> * delete UnaryExpression<sub>[?Yield]</sub> * void UnaryExpression<sub>[?Yield]</sub> * typeof UnaryExpression<sub>[?Yield]</sub> * ++ UnaryExpression<sub>[?Yield]</sub> * -- UnaryExpression<sub>[?Yield]</sub> * + UnaryExpression<sub>[?Yield]</sub> * - UnaryExpression<sub>[?Yield]</sub> * ~ UnaryExpression<sub>[?Yield]</sub> * ! UnaryExpression<sub>[?Yield]</sub> * </pre> */ private Expression unaryExpression() { long begin = ts.beginPosition(); Token tok = token(); switch (tok) { case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: { consume(tok); Expression operand = unaryExpression(); UnaryExpression unary = new UnaryExpression(begin, ts.endPosition(), unaryOp(tok, false), operand); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(operand, ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); } if (tok == Token.DELETE) { if (operand instanceof Identifier) { reportStrictModeSyntaxError(unary, Messages.Key.StrictModeInvalidDeleteOperand); } } return unary; } default: { Expression lhs = leftHandSideExpression(true); if (noLineTerminator()) { tok = token(); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(lhs, ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); consume(tok); return new UnaryExpression(begin, ts.endPosition(), unaryOp(tok, true), lhs); } } return lhs; } } } private static UnaryExpression.Operator unaryOp(Token tok, boolean postfix) { switch (tok) { case DELETE: return UnaryExpression.Operator.DELETE; case VOID: return UnaryExpression.Operator.VOID; case TYPEOF: return UnaryExpression.Operator.TYPEOF; case INC: return postfix ? UnaryExpression.Operator.POST_INC : UnaryExpression.Operator.PRE_INC; case DEC: return postfix ? UnaryExpression.Operator.POST_DEC : UnaryExpression.Operator.PRE_DEC; case ADD: return UnaryExpression.Operator.POS; case SUB: return UnaryExpression.Operator.NEG; case BITNOT: return UnaryExpression.Operator.BITNOT; case NOT: return UnaryExpression.Operator.NOT; default: throw new IllegalStateException(); } } private Expression binaryExpression(boolean allowIn) { Expression lhs = unaryExpression(); return binaryExpression(allowIn, lhs, BinaryExpression.Operator.OR.getPrecedence()); } private Expression binaryExpression(boolean allowIn, Expression lhs, int minpred) { // Recursive-descent parsers require multiple levels of recursion to // parse binary expressions, to avoid this we're using precedence // climbing here for (;;) { Token tok = token(); if (tok == Token.IN && !allowIn) { break; } BinaryExpression.Operator op = binaryOp(tok); int pred = (op != null ? op.getPrecedence() : -1); if (pred < minpred) { break; } consume(tok); Expression rhs = unaryExpression(); for (;;) { BinaryExpression.Operator op2 = binaryOp(token()); int pred2 = (op2 != null ? op2.getPrecedence() : -1); if (pred2 <= pred) { break; } rhs = binaryExpression(allowIn, rhs, pred2); } lhs = new BinaryExpression(op, lhs, rhs); } return lhs; } private static BinaryExpression.Operator binaryOp(Token token) { switch (token) { case OR: return BinaryExpression.Operator.OR; case AND: return BinaryExpression.Operator.AND; case BITOR: return BinaryExpression.Operator.BITOR; case BITXOR: return BinaryExpression.Operator.BITXOR; case BITAND: return BinaryExpression.Operator.BITAND; case EQ: return BinaryExpression.Operator.EQ; case NE: return BinaryExpression.Operator.NE; case SHEQ: return BinaryExpression.Operator.SHEQ; case SHNE: return BinaryExpression.Operator.SHNE; case LT: return BinaryExpression.Operator.LT; case LE: return BinaryExpression.Operator.LE; case GT: return BinaryExpression.Operator.GT; case GE: return BinaryExpression.Operator.GE; case IN: return BinaryExpression.Operator.IN; case INSTANCEOF: return BinaryExpression.Operator.INSTANCEOF; case SHL: return BinaryExpression.Operator.SHL; case SHR: return BinaryExpression.Operator.SHR; case USHR: return BinaryExpression.Operator.USHR; case ADD: return BinaryExpression.Operator.ADD; case SUB: return BinaryExpression.Operator.SUB; case MUL: return BinaryExpression.Operator.MUL; case DIV: return BinaryExpression.Operator.DIV; case MOD: return BinaryExpression.Operator.MOD; default: return null; } } /** * <strong>[12.12] Conditional Operator</strong><br> * <strong>[12.13] Assignment Operators</strong> * * <pre> * ConditionalExpression<sub>[In, Yield]</sub> : * LogicalORExpression<sub>[?In, ?Yield]</sub> * LogicalORExpression<sub>[?In, ?Yield]</sub> ? AssignmentExpression<sub>[In, ?Yield]</sub> : AssignmentExpression<sub>[?In, ?Yield]</sub> * AssignmentExpression<sub>[In, Yield]</sub> : * ConditionalExpression<sub>[?In, ?Yield]</sub> * <sub>[+Yield]</sub> YieldExpression<sub>[?In]</sub> * ArrowFunction<sub>[?In]</sub> * LeftHandSideExpression<sub>[?Yield]</sub> = AssignmentExpression<sub>[?In, ?Yield]</sub> * LeftHandSideExpression<sub>[?Yield]</sub> AssignmentOperator AssignmentExpression<sub>[?In, ?Yield]</sub> * </pre> */ private Expression assignmentExpression(boolean allowIn) { int count = context.countLiterals(); Expression expr = assignmentExpression(allowIn, count); if (count < context.countLiterals()) { objectLiteral_StaticSemantics(count); } return expr; } private Expression assignmentExpressionNoValidation(boolean allowIn) { return assignmentExpression(allowIn, context.countLiterals()); } private Expression assignmentExpression(boolean allowIn, int oldCount) { if (token() == Token.YIELD) { if (context.kind == ContextKind.Generator) { return yieldExpression(allowIn); } else if (context.kind == ContextKind.Function && isEnabled(CompatibilityOption.LegacyGenerator)) { throw new RetryGenerator(); } else if (context.kind == ContextKind.GeneratorComprehension && context.yieldAllowed) { // yield nested in generator comprehension, nested in generator reportSyntaxError(Messages.Key.InvalidYieldExpression); } } long position = ts.position(), lineinfo = ts.lineinfo(); Expression left = binaryExpression(allowIn); Token tok = token(); if (tok == Token.HOOK) { consume(Token.HOOK); Expression then = assignmentExpression(true); consume(Token.COLON); Expression otherwise = assignmentExpression(allowIn); return new ConditionalExpression(left, then, otherwise); } else if (tok == Token.ARROW) { // discard parsed object literals if (oldCount < context.countLiterals()) { // TODO: still need to verify this // perform Static Semantics early error detection since the parameter production is // first parsed as an Expression objectLiteral_StaticSemantics(oldCount); } ts.reset(position, lineinfo); return arrowFunction(allowIn); } else if (tok == Token.ASSIGN) { LeftHandSideExpression lhs = validateAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(Token.ASSIGN); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else if (isAssignmentOperator(tok)) { LeftHandSideExpression lhs = validateSimpleAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(tok); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else { return left; } } private static AssignmentExpression.Operator assignmentOp(Token token) { switch (token) { case ASSIGN: return AssignmentExpression.Operator.ASSIGN; case ASSIGN_ADD: return AssignmentExpression.Operator.ASSIGN_ADD; case ASSIGN_SUB: return AssignmentExpression.Operator.ASSIGN_SUB; case ASSIGN_MUL: return AssignmentExpression.Operator.ASSIGN_MUL; case ASSIGN_DIV: return AssignmentExpression.Operator.ASSIGN_DIV; case ASSIGN_MOD: return AssignmentExpression.Operator.ASSIGN_MOD; case ASSIGN_SHL: return AssignmentExpression.Operator.ASSIGN_SHL; case ASSIGN_SHR: return AssignmentExpression.Operator.ASSIGN_SHR; case ASSIGN_USHR: return AssignmentExpression.Operator.ASSIGN_USHR; case ASSIGN_BITAND: return AssignmentExpression.Operator.ASSIGN_BITAND; case ASSIGN_BITOR: return AssignmentExpression.Operator.ASSIGN_BITOR; case ASSIGN_BITXOR: return AssignmentExpression.Operator.ASSIGN_BITXOR; default: throw new IllegalStateException(); } } /** * <strong>[12.13] Assignment Operators</strong> * * <pre> * AssignmentOperator : <b>one of</b> * *= /= %= += -= <<= >>= >>>= &= ^= |= * </pre> */ private boolean isAssignmentOperator(Token tok) { switch (tok) { case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: return true; default: return false; } } /** * <strong>[12.14] Comma Operator</strong> * * <pre> * Expression<sub>[In, Yield]</sub> : * AssignmentExpression<sub>[?In, ?Yield]</sub> * Expression<sub>[?In, ?Yield]</sub> , AssignmentExpression<sub>[?In, ?Yield]</sub> * </pre> */ private Expression expression(boolean allowIn) { Expression expr = assignmentExpression(allowIn); if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); expr = assignmentExpression(allowIn); list.add(expr); } return new CommaExpression(list); } return expr; } /** * <strong>[11.9] Automatic Semicolon Insertion</strong> * * <pre> * </pre> */ private void semicolon() { switch (token()) { case SEMI: consume(Token.SEMI); // fall-through case RC: case EOF: break; default: if (noLineTerminator()) { reportSyntaxError(Messages.Key.MissingSemicolon); } } } /** * Returns {@code true} if the last and the current token are not separated from each other by a * line-terminator */ private boolean noLineTerminator() { return !ts.hasCurrentLineTerminator(); } /** * Returns {@code true} if the current and the next token are not separated from each other by a * line-terminator */ private boolean noNextLineTerminator() { return !ts.hasNextLineTerminator(); } /** * Returns true if the current token is of type {@link Token#NAME} and its name is {@code name} */ private boolean isName(String name) { Token tok = token(); return (tok == Token.NAME && name.equals(getName(tok))); } /** * Returns the token's name */ private String getName(Token tok) { if (tok == Token.NAME) { return ts.getString(); } return tok.getName(); } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private String identifierName() { Token tok = token(); if (!isIdentifierName(tok)) { reportTokenNotIdentifierName(tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private static boolean isIdentifierName(Token tok) { switch (tok) { case NAME: // Literals case NULL: case FALSE: case TRUE: // Keywords case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case EXTENDS: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: case YIELD: // Future Reserved Words case ENUM: case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: return true; default: return false; } } /** * <strong>[11.6.2] Reserved Words</strong> */ private boolean isReservedWord(Token tok) { assert context.strictMode != StrictMode.Unknown : "unknown strict-mode"; switch (tok) { case FALSE: case NULL: case TRUE: return true; default: return isKeyword(tok) || isFutureReservedWord(tok); } } /** * <strong>[11.6.2.1] Keywords</strong> */ private boolean isKeyword(Token tok) { assert context.strictMode != StrictMode.Unknown : "unknown strict-mode"; switch (tok) { case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case EXTENDS: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: return true; case YIELD: return (context.strictMode == StrictMode.Strict); default: return false; } } /** * <strong>[11.6.2.2] Future Reserved Words</strong> */ private boolean isFutureReservedWord(Token tok) { assert context.strictMode != StrictMode.Unknown : "unknown strict-mode"; switch (tok) { case ENUM: return true; case IMPLEMENTS: case INTERFACE: case LET: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: return (context.strictMode == StrictMode.Strict); default: return false; } } /** * <strong>[11.8.3] Numeric Literals</strong> */ private double numericLiteral() { double number = ts.getNumber(); consume(Token.NUMBER); return number; } /** * <strong>[11.8.4] String Literals</strong> */ private String stringLiteral() { String string = ts.getString(); consume(Token.STRING); return string; } }
package com.github.lunatrius.profiles; import com.github.lunatrius.core.version.VersionChecker; import com.github.lunatrius.profiles.command.ProfileCommand; import com.github.lunatrius.profiles.lib.Reference; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.relauncher.Side; import net.minecraftforge.client.ClientCommandHandler; @Mod(modid = Reference.MODID, name = Reference.NAME) public class Profiles { @EventHandler public void preInit(FMLPreInitializationEvent event) { Reference.logger = event.getModLog(); Reference.config = event.getSuggestedConfigurationFile(); if (Loader.isModLoaded("LunatriusCore")) { registerVersionChecker(event.getModMetadata()); } } private void registerVersionChecker(ModMetadata modMetadata) { VersionChecker.registerMod(modMetadata, Reference.FORGE); } @EventHandler public void init(FMLInitializationEvent event) { if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) { ClientCommandHandler.instance.registerCommand(new ProfileCommand()); } else { Reference.logger.warn("WARNING! You're loading a CLIENT only mod on a server!"); } } }
package com.github.msemys.esjc.http; import com.github.msemys.esjc.UserCredentials; import com.github.msemys.esjc.http.handler.HttpResponseHandler; import com.github.msemys.esjc.util.concurrent.ResettableLatch; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.util.concurrent.DefaultThreadFactory; import java.net.InetSocketAddress; import java.time.Duration; import java.util.Base64; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.msemys.esjc.util.Numbers.isPositive; import static com.github.msemys.esjc.util.Preconditions.*; import static com.github.msemys.esjc.util.Strings.*; import static io.netty.buffer.Unpooled.copiedBuffer; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * HTTP client without pipelining support */ public class HttpClient implements AutoCloseable { private final EventLoopGroup group = new NioEventLoopGroup(0, new DefaultThreadFactory("es-http")); private final Bootstrap bootstrap; private final String host; private final boolean acceptGzip; private final long operationTimeoutMillis; private final Queue<HttpOperation> queue = new ConcurrentLinkedQueue<>(); private final AtomicBoolean isProcessing = new AtomicBoolean(); private final ResettableLatch received = new ResettableLatch(false); private volatile Channel channel; private HttpClient(Builder builder) { host = builder.address.getHostString(); acceptGzip = builder.acceptGzip; operationTimeoutMillis = builder.operationTimeout.toMillis(); bootstrap = new Bootstrap() .remoteAddress(builder.address) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) builder.connectTimeout.toMillis()) .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpClientCodec()); if (acceptGzip) { pipeline.addLast("content-decompressor", new HttpContentDecompressor()); } pipeline.addLast("object-aggregator", new HttpObjectAggregator(builder.maxContentLength)); pipeline.addLast("logger", new LoggingHandler(HttpClient.class, LogLevel.TRACE)); pipeline.addLast("response-handler", new HttpResponseHandler()); } }); } public CompletableFuture<FullHttpResponse> send(HttpRequest request) { checkNotNull(request, "request is null"); checkState(isRunning(), "HTTP client is closed"); request.headers().set(HttpHeaders.Names.HOST, host); if (acceptGzip) { request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } CompletableFuture<FullHttpResponse> response = new CompletableFuture<>(); enqueue(new HttpOperation(request, response)); return response; } private void enqueue(HttpOperation operation) { checkNotNull(operation, "operation is null"); queue.offer(operation); if (isProcessing.compareAndSet(false, true)) { executor().execute(this::processQueue); } } private void processQueue() { do { HttpOperation operation; while ((operation = queue.poll()) != null) { if (channel == null || !channel.isActive()) { try { ChannelFuture future = bootstrap.connect().await(); if (future.isSuccess()) { channel = future.channel(); } else { operation.response.completeExceptionally(future.cause()); continue; } } catch (Exception e) { operation.response.completeExceptionally(e); continue; } } write(operation); } isProcessing.set(false); } while (isRunning() && !queue.isEmpty() && isProcessing.compareAndSet(false, true)); } private void write(HttpOperation operation) { received.reset(); operation.response.whenComplete((r, t) -> received.release()); HttpResponseHandler responseHandler = channel.pipeline().get(HttpResponseHandler.class); responseHandler.pendingResponse = operation.response; try { channel.writeAndFlush(operation.request).await(); if (!received.await(operationTimeoutMillis, MILLISECONDS)) { channel.close().awaitUninterruptibly(); String message = String.format("%s %s request never got response from server.", operation.request.getMethod().name(), operation.request.getUri()); operation.response.completeExceptionally(new TimeoutException(message)); } } catch (InterruptedException e) { operation.response.completeExceptionally(e); } finally { responseHandler.pendingResponse = null; channel.closeFuture().awaitUninterruptibly(); } } private boolean isRunning() { return !group.isShuttingDown(); } @Override public void close() { group.shutdownGracefully(); HttpOperation operation; while ((operation = queue.poll()) != null) { operation.response.completeExceptionally(new HttpClientException("Client closed")); } } private Executor executor() { return group; } private static void addAuthorizationHeader(FullHttpRequest request, UserCredentials userCredentials) { checkNotNull(request, "request is null"); checkNotNull(userCredentials, "userCredentials is null"); byte[] encodedCredentials = Base64.getEncoder().encode(toBytes(userCredentials.username + ":" + userCredentials.password)); request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + newString(encodedCredentials)); } public static FullHttpRequest newRequest(HttpMethod method, String uri, UserCredentials userCredentials) { checkNotNull(method, "method is null"); checkArgument(!isNullOrEmpty(uri), "uri is null or empty"); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); if (userCredentials != null) { addAuthorizationHeader(request, userCredentials); } return request; } public static FullHttpRequest newRequest(HttpMethod method, String uri, String body, String contentType, UserCredentials userCredentials) { checkNotNull(method, "method is null"); checkArgument(!isNullOrEmpty(uri), "uri is null or empty"); checkNotNull(body, "body is null"); checkArgument(!isNullOrEmpty(contentType), "contentType is null or empty"); ByteBuf data = copiedBuffer(body, UTF_8); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri, data); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); request.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, data.readableBytes()); if (userCredentials != null) { addAuthorizationHeader(request, userCredentials); } return request; } /** * Creates a new HTTP client builder. * * @return HTTP client builder */ public static Builder newBuilder() { return new Builder(); } /** * HTTP client builder. */ public static class Builder { private InetSocketAddress address; private Duration connectTimeout; private Duration operationTimeout; private Boolean acceptGzip; private Integer maxContentLength; /** * Sets server address. * * @param host the host name. * @param port the port number. * @return the builder reference */ public Builder address(String host, int port) { return address(new InetSocketAddress(host, port)); } /** * Sets server address. * * @param address the server address. * @return the builder reference */ public Builder address(InetSocketAddress address) { this.address = address; return this; } /** * Sets connection establishment timeout (by default, 10 seconds). * * @param connectTimeout connection establishment timeout. * @return the builder reference */ public Builder connectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } /** * Sets the amount of time before an operation is considered to have timed out (by default, 7 seconds). * * @param operationTimeout the amount of time before an operation is considered to have timed out. * @return the builder reference */ public Builder operationTimeout(Duration operationTimeout) { this.operationTimeout = operationTimeout; return this; } /** * Specifies whether or not the client accepts compressed content (by default, does not accept compressed content). * * @param acceptGzip {@code true} to accept. * @return the builder reference */ public Builder acceptGzip(boolean acceptGzip) { this.acceptGzip = acceptGzip; return this; } /** * Sets the maximum length of the response content in bytes (by default, 128 megabytes). * * @param maxContentLength the maximum length of the response content in bytes. * @return the builder reference */ public Builder maxContentLength(int maxContentLength) { this.maxContentLength = maxContentLength; return this; } /** * Builds a HTTP client. * * @return HTTP client */ public HttpClient build() { checkNotNull(address, "address is null"); if (connectTimeout == null) { connectTimeout = Duration.ofSeconds(10); } if (operationTimeout == null) { operationTimeout = Duration.ofSeconds(7); } if (acceptGzip == null) { acceptGzip = false; } if (maxContentLength == null) { maxContentLength = 128 * 1024 * 1024; } else { checkArgument(isPositive(maxContentLength), "maxContentLength should be positive"); } return new HttpClient(this); } } private static class HttpOperation { final HttpRequest request; final CompletableFuture<FullHttpResponse> response; HttpOperation(HttpRequest request, CompletableFuture<FullHttpResponse> response) { checkNotNull(request, "request is null"); checkNotNull(response, "response is null"); this.request = request; this.response = response; } } }
package com.googlecode.pngtastic.core; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * Represents a png image * * @author rayvanderborght */ public class PngImage { private final Logger log; public static final long SIGNATURE = 0x89504e470d0a1a0aL; private String fileName; public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } private List<PngChunk> chunks = new ArrayList<>(); public List<PngChunk> getChunks() { return this.chunks; } private long width; public long getWidth() { return this.width; } private long height; public long getHeight() { return this.height; } private short bitDepth; public short getBitDepth() { return this.bitDepth; } private short colorType; public short getColorType() { return this.colorType; } private short interlace; public short getInterlace() { return this.interlace; } public void setInterlace(short interlace) { this.interlace = interlace; } private PngChunk palette; public PngChunk getPalette() { return palette; } private PngImageType imageType; public PngImage() { this.log = new Logger(Logger.NONE); } public PngImage(Logger log) { this.log = log; } public PngImage(String fileName, String logLevel) throws FileNotFoundException { this(new BufferedInputStream(new FileInputStream(fileName)), logLevel); this.fileName = fileName; } public PngImage(InputStream ins) { this(ins, null); } public PngImage(InputStream ins, String logLevel) { this(new Logger(logLevel)); try { DataInputStream dis = new DataInputStream(ins); readSignature(dis); int length; PngChunk chunk; do { length = getChunkLength(dis); byte[] type = getChunkType(dis); byte[] data = getChunkData(dis, length); long crc = getChunkCrc(dis); chunk = new PngChunk(type, data); // log.debug("chunk: " + chunk.getTypeString()); // if ("pHYs".equals(chunk.getTypeString())) { // for (byte x : chunk.getData()) // log.debug("data: " + x + "," + String.format("%x", x)); if (!chunk.verifyCRC(crc)) { throw new PngException("Corrupted file, crc check failed"); } addChunk(chunk); } while (length > 0 && !PngChunk.IMAGE_TRAILER.equals(chunk.getTypeString())); } catch (IOException e) { throw new PngException("Error: " + e.getMessage(), e); } } public File export(String fileName, byte[] bytes) throws IOException { File out = new File(fileName); writeFileOutputStream(out, bytes); return out; } FileOutputStream writeFileOutputStream(File out, byte[] bytes) throws IOException { FileOutputStream outs = null; try { outs = new FileOutputStream(out); outs.write(bytes); } finally { if (outs != null) { outs.close(); } } return outs; } public DataOutputStream writeDataOutputStream(OutputStream output) throws IOException { DataOutputStream outs = new DataOutputStream(output); outs.writeLong(PngImage.SIGNATURE); for (PngChunk chunk : chunks) { log.debug("export: %s", chunk.toString()); outs.writeInt(chunk.getLength()); outs.write(chunk.getType()); outs.write(chunk.getData()); int i = (int)chunk.getCRC(); outs.writeInt(i); } outs.close(); return outs; } public void addChunk(PngChunk chunk) { switch (chunk.getTypeString()) { case PngChunk.IMAGE_HEADER: this.width = chunk.getWidth(); this.height = chunk.getHeight(); this.bitDepth = chunk.getBitDepth(); this.colorType = chunk.getColorType(); this.interlace = chunk.getInterlace(); break; case PngChunk.PALETTE: this.palette = chunk; break; } this.chunks.add(chunk); } public byte[] getImageData() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); // Write all the IDAT data for (PngChunk chunk : chunks) { if (chunk.getTypeString().equals(PngChunk.IMAGE_DATA)) { out.write(chunk.getData()); } } return out.toByteArray(); } catch (IOException e) { System.out.println("Couldn't get image data: " + e); } return null; } public int getSampleBitCount() { this.imageType = (this.imageType == null) ? PngImageType.forColorType(this.colorType) : this.imageType; return this.imageType.channelCount() * this.bitDepth; } private int getChunkLength(DataInputStream ins) throws IOException { return ins.readInt(); } private byte[] getChunkType(InputStream ins) throws PngException { return getChunkData(ins, 4); } private byte[] getChunkData(InputStream ins, int length) throws PngException { byte[] data = new byte[length]; try { int actual = ins.read(data); if (actual < length) { throw new PngException(String.format("Expected %d bytes but got %d", length, actual)); } } catch (IOException e) { throw new PngException("Error reading chunk data", e); } return data; } private long getChunkCrc(DataInputStream ins) throws IOException { int i = ins.readInt(); long crc = i & 0x00000000ffffffffL; // Make it unsigned. return crc; } private static void readSignature(DataInputStream ins) throws PngException, IOException { long signature = ins.readLong(); if (signature != PngImage.SIGNATURE) { throw new PngException("Bad png signature"); } } }
package com.heroku.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("com.heroku") public class WebMvcJspApplication extends SpringBootServletInitializer { private static Logger LOGGER = LoggerFactory.getLogger(WebMvcJspApplication.class); @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(WebMvcJspApplication.class); } public static void main(String[] args) throws Exception { LOGGER.info("Starting Main Application..."); SpringApplication.run(WebMvcJspApplication.class, args); LOGGER.info("Access URLs: http://localhost:8080\n"); } }
package com.iheartradio.m3u8; import com.iheartradio.m3u8.data.Playlist; import java.io.InputStream; import java.util.HashMap; import java.util.Map; class ExtendedM3uParser { private final ExtendedM3uScanner mScanner; private final Encoding mEncoding; private final Map<String, IExtTagHandler> mExtTagHandlers = new HashMap<String, IExtTagHandler>(); ExtendedM3uParser(InputStream inputStream, Encoding encoding) { mScanner = new ExtendedM3uScanner(inputStream, encoding); mEncoding = encoding; // TODO implement the EXT tag handlers and add them here putHandlers( ExtTagHandler.EXTM3U_HANDLER, ExtTagHandler.EXT_X_VERSION_HANDLER, MediaPlaylistTagHandler.EXT_X_KEY, MasterPlaylistTagHandler.EXT_X_MEDIA, MasterPlaylistTagHandler.EXT_X_STREAM_INF, MasterPlaylistTagHandler.EXT_X_I_FRAME_STREAM_INF, MediaPlaylistTagHandler.EXT_X_TARGETDURATION, MediaPlaylistTagHandler.EXT_X_START, MediaPlaylistTagHandler.EXT_X_PLAYLIST_TYPE, MediaPlaylistTagHandler.EXT_X_MEDIA_SEQUENCE, MediaPlaylistTagHandler.EXT_X_ALLOW_CACHE, MediaPlaylistTagHandler.EXT_X_I_FRAMES_ONLY, MediaPlaylistTagHandler.EXTINF, MediaPlaylistTagHandler.EXT_X_ENDLIST ); } Playlist parse() throws ParseException { final ParseState state = new ParseState(mEncoding); final LineHandler playlistHandler = new PlaylistHandler(); final LineHandler trackHandler = new TrackHandler(); try { while (mScanner.hasNext()) { final String line = mScanner.next(); checkWhitespace(line); if (line.length() == 0 || isComment(line)) { continue; } else { if (isExtTag(line)) { final String tagKey = getExtTagKey(line); final IExtTagHandler handler = mExtTagHandlers.get(tagKey); if (handler == null) { // TODO provide lenient mode that ignores unrecognized EXT tags throw ParseException.create(ParseExceptionType.UNSUPPORTED_EXT_TAG_DETECTED, tagKey, line); } else { handler.handle(line, state); } } else if (state.isMaster()) { playlistHandler.handle(line, state); } else if (state.isMedia()) { trackHandler.handle(line, state); } else { throw ParseException.create(ParseExceptionType.UNKNOWN_PLAYLIST_TYPE, line); } } } return state.buildPlaylist(); } catch (ParseException exception) { exception.setInput(mScanner.getInput()); throw exception; } finally { mScanner.close(); } } private void putHandlers(IExtTagHandler... handlers) { if (handlers != null) { for (IExtTagHandler handler : handlers) { mExtTagHandlers.put(handler.getTag(), handler); } } } private void checkWhitespace(final String line) throws ParseException { if (!isComment(line)) { if (line.length() != line.trim().length()) { throw ParseException.create(ParseExceptionType.WHITESPACE_IN_TRACK, line); } } } private boolean isComment(final String line) { return line.startsWith(Constants.COMMENT_PREFIX) && !isExtTag(line); } private boolean isExtTag(final String line) { return line.startsWith(Constants.EXT_TAG_PREFIX); } private String getExtTagKey(final String line) { int index = line.indexOf(Constants.EXT_TAG_END); if (index == -1) { return line.substring(1); } else { return line.substring(1, index); } } }
package com.iheartradio.m3u8.data; import java.util.Objects; public class PlaylistData { private final String mUri; private final StreamInfo mStreamInfo; private PlaylistData(String uri, StreamInfo streamInfo) { mUri = uri; mStreamInfo = streamInfo; } public String getUri() { return mUri; } public boolean hasStreamInfo() { return mStreamInfo != null; } public StreamInfo getStreamInfo() { return mStreamInfo; } public Builder buildUpon() { return new Builder(mUri, mStreamInfo); } @Override public int hashCode() { return Objects.hash(mUri, mStreamInfo); } @Override public boolean equals(Object o) { if (!(o instanceof PlaylistData)) { return false; } PlaylistData other = (PlaylistData) o; return Objects.equals(mUri, other.mUri) && Objects.equals(mStreamInfo, other.mStreamInfo); } @Override public String toString() { return "PlaylistData [mStreamInfo=" + mStreamInfo + ", mUri=" + mUri + "]"; } public static class Builder { private String mUri; private StreamInfo mStreamInfo; public Builder() { } private Builder(String uri, StreamInfo streamInfo) { mUri = uri; mStreamInfo = streamInfo; } public Builder withPath(String path) { mUri = path; return this; } public Builder withUri(String uri) { mUri = uri; return this; } public Builder withStreamInfo(StreamInfo streamInfo) { mStreamInfo = streamInfo; return this; } public PlaylistData build() { return new PlaylistData(mUri, mStreamInfo); } } }
package com.j256.ormlite.dao; import java.io.Closeable; import java.sql.SQLException; import java.util.Iterator; import com.j256.ormlite.support.DatabaseResults; /** * Extension to Iterator to provide a close() method. This should be in the JDK. * * <p> * <b>NOTE:</b> You must call {@link CloseableIterator#close()} method when you are done otherwise the underlying SQL * statement and connection may be kept open. * </p> * * @author graywatson */ public interface CloseableIterator<T> extends Iterator<T>, Closeable { /** * Close any underlying SQL statements but swallow any SQLExceptions. */ public void closeQuietly(); /** * Return the underlying database results object if any. May return null. This should not be used unless you know * what you are doing. For example, if you shift the cursor in the raw-results, this could cause problems when you * come back here to go the next result. */ public DatabaseResults getRawResults(); /** * Move to the next item in the iterator without calling {@link #next()}. */ public void moveToNext(); /** * Move to the first result and return it or null if none. This may not work with the default iterator depending on * your database. */ public T first() throws SQLException; /** * Moves to the previous result and return it or null if none. This may not work with the default iterator depending * on your database. */ public T previous() throws SQLException; /** * Return the current result object that we have accessed or null if none. */ public T current() throws SQLException; /** * Returns the {@link #next()} object in the table or null if none. * * @throws SQLException * Throws a SQLException on error since {@link #next()} cannot throw because it is part of the * {@link Iterator} definition. It will <i>not</i> throw if there is no next. */ public T nextThrow() throws SQLException; /** * Move a relative position in the list and return that result or null if none. Moves forward (positive value) or * backwards (negative value) the list of results. moveRelative(1) should be the same as {@link #next()}. * moveRelative(-1) is the same as {@link #previous} result. This may not work with the default iterator depending * on your database. * * @param offset * Number of rows to move. Positive moves forward in the results. Negative moves backwards. * @return The object at the new position or null of none. */ public T moveRelative(int offset) throws SQLException; /** * Move to an absolute position in the list and return that result or null if none. This may not be supported * depending on your database or depending on the type of iterator and where you are moving. For example, in * JDBC-land, often the iterator created can only move forward and will throw an exception if you attempt to move to * an absolute position behind the current position. * * @param position * Row number in the result list to move to. * @return The object at the new position or null of none. */ public T moveAbsolute(int position) throws SQLException; }
package com.jraska.vsb.or1.io; import com.jraska.common.ArgumentCheck; import com.jraska.vsb.or1.data.Input; import com.jraska.vsb.or1.data.Job; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public final class SimpleTextParser implements IInputParser { //region IInputParser impl @Override public Input parse(InputStream inputStream) { ArgumentCheck.notNull(inputStream); Scanner scanner = new Scanner(inputStream); int machinesCount = scanner.nextInt(); int jobsCount = scanner.nextInt(); int[][] data = new int[jobsCount][machinesCount]; for (int i = 0; i < machinesCount; i++) { for (int j = 0; j < jobsCount; j++) { //save in index reverse order to have job columns in lines data[j][i] = scanner.nextInt(); } } List<Job> jobs = new ArrayList<Job>(); for (int i = 0; i < jobsCount; i++) { Job job = new Job(data[i]); //job data are stored in line jobs.add(job); } return new Input(machinesCount, jobs); } //endregion }
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.CommandExecutor; import com.laytonsmith.PureUtilities.Common.ArrayUtils; import com.laytonsmith.PureUtilities.Common.MutableObject; import com.laytonsmith.PureUtilities.Common.OSUtils; import com.laytonsmith.PureUtilities.Common.StreamUtils; import com.laytonsmith.PureUtilities.Common.StringUtils; import com.laytonsmith.PureUtilities.TermColors; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.annotations.api; import com.laytonsmith.annotations.core; import com.laytonsmith.annotations.noboilerplate; import com.laytonsmith.annotations.seealso; import com.laytonsmith.core.ArgumentValidation; import com.laytonsmith.core.CHLog; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.Prefs; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CByteArray; import com.laytonsmith.core.constructs.CClosure; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CSecureString; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.environments.GlobalEnv; import com.laytonsmith.core.exceptions.CRE.CRECastException; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CREIOException; import com.laytonsmith.core.exceptions.CRE.CREInsufficientPermissionException; import com.laytonsmith.core.exceptions.CRE.CREPluginInternalException; import com.laytonsmith.core.exceptions.CRE.CREShellException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.natives.interfaces.Mixed; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; import java.lang.reflect.Field; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; @core public class Cmdline { public static String docs() { return "This class contains functions that are mostly only useful for command line scripts, but in general may be used by any script. For" + " more information on running MethodScript from the command line, see [[CommandHelper/Command_Line_Scripting|this wiki page]]."; } @api @noboilerplate public static class sys_out extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public CVoid exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { String msg = Static.MCToANSIColors(args[0].val()); StreamUtils.GetSystemOut().print(msg); if(msg.contains("\033")) { //We have color codes in it, we need to reset them StreamUtils.GetSystemOut().print(TermColors.reset()); } StreamUtils.GetSystemOut().println(); return CVoid.VOID; } @Override public String getName() { return "sys_out"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "void {text} Writes the text to the system's std out. Unlike console(), this does not use anything else to format the output, though in many" + " cases they will behave the same. However, colors and other formatting characters will not \"bleed\" through, so" + " sys_out(color(RED) . 'This is red') will not cause the next line to also be red, so if you need to print multiple lines out, you should" + " manually add \\n to create your linebreaks, and only make one call to sys_out."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "#Note, this is guaranteed to print to standard out\nsys_out('Hello World!')", ":Hello World!") }; } } @api @noboilerplate public static class sys_err extends AbstractFunction { @Override public Class[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public CVoid exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { String msg = Static.MCToANSIColors(args[0].val()); PrintStream se = StreamUtils.GetSystemErr(); se.print(msg); if(msg.contains("\033")) { //We have color codes in it, we need to reset them se.print(TermColors.reset()); } se.println(); return CVoid.VOID; } @Override public String getName() { return "sys_err"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "void {text} Writes the text to the system's std err. Unlike console(), this does not use anything else to format the output, though in many" + " cases they will behave nearly the same. However, colors and other formatting characters will not \"bleed\" through, so" + " sys_err(color(RED) . 'This is red') will not cause the next line to also be red, so if you need to print multiple lines out, you should" + " manually add \\n to create your linebreaks, and only make one call to sys_err."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "#Note this is guaranteed to print to standard err\nsys_out('Hello World!')", ":Hello World!") }; } } @api @noboilerplate public static class print_out extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public CVoid exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { String msg = Static.MCToANSIColors(args[0].val()); PrintStream so = StreamUtils.GetSystemOut(); so.print(msg); so.flush(); return CVoid.VOID; } @Override public String getName() { return "print_out"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "void {text} Writes the text to the system's std out, but does not automatically add a newline at the end." + " Unlike console(), this does not use anything else to format the output, though in many" + " cases they will behave the same. Unlike other print methdods, colors and other formatting characters WILL" + " \"bleed\" through, so" + " print_out(color(RED) . 'This is red') will also cause the next line to also be red," + " so if you need to print multiple lines out, you should manually reset the color with print_out(color(RESET))."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate public static class print_err extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public CVoid exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { String msg = Static.MCToANSIColors(args[0].val()); StreamUtils.GetSystemErr().print(msg); StreamUtils.GetSystemErr().flush(); return CVoid.VOID; } @Override public String getName() { return "print_err"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "void {text} Writes the text to the system's std err, but does not automatically add a newline at the end." + " Unlike console(), this does not use anything else to format the output, though in many" + " cases they will behave the same. Unlike other print methdods, colors and other formatting characters WILL" + " \"bleed\" through, so" + " print_err(color(RED) . 'This is red') will also cause the next line to also be red," + " so if you need to print multiple lines out, you should manually reset the color with print_out(color(RESET))."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api(environments = {GlobalEnv.class}) @noboilerplate public static class exit extends AbstractFunction implements Optimizable { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return false; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { int exit_code = 0; if(args.length == 1) { exit_code = Static.getInt32(args[0], t); } if(Static.InCmdLine(environment)) { System.exit(exit_code); } return new Echoes.die().exec(t, environment, args); } @Override public String getName() { return "exit"; } @Override public Integer[] numArgs() { return new Integer[]{0, 1}; } @Override public String docs() { return "void {[int]} Exits the program. If this is being run from the command line, works by exiting the interpreter, with " + " the specified exit code (defaulting to 0). If this is being run from in-game, works just like die()."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.TERMINAL ); } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "#Causes the JVM to exit with an exit code of 0\nexit(0)", ""), new ExampleScript("Basic usage", "#Causes the JVM to exit with an exit code of 1\nexit(1)", "")}; } } @api public static class sys_properties extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args.length == 1) { String propName = args[0].val(); String prop; if(propName.startsWith("methodscript.")) { prop = getMethodScriptProperties().get(propName); } else { prop = System.getProperty(propName); } if(prop == null) { return CNull.NULL; } return new CString(prop, t); } else { CArray ca = CArray.GetAssociativeArray(t); for(String key : System.getProperties().stringPropertyNames()) { ca.set(key, System.getProperty(key)); } Map<String, String> msProps = getMethodScriptProperties(); for(String key : msProps.keySet()) { ca.set(key, msProps.get(key)); } return ca; } } private Map<String, String> getMethodScriptProperties() { Map<String, String> map = new HashMap<>(); for(Prefs.PNames name : Prefs.PNames.values()) { map.put("methodscript.preference." + name.config(), Prefs.pref(name).toString()); } return map; } @Override public String getName() { return "sys_properties"; } @Override public Integer[] numArgs() { return new Integer[]{0, 1}; } @Override public String docs() { return "mixed {[propertyName]} If propertyName is set, that single property is returned, or null if that property doesn't exist. If propertyName is not set, an" + " associative array with all the system properties is returned. This mechanism hooks into Java's system property mechanism, and is just a wrapper for" + " that. System properties are more reliable than environmental variables, and so are preferred in cases where they exist. For more information about system" + " properties, see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html. In addition, known preferences listed in preferences.ini" + " are also included, starting with the prefix \"methodscript.preference.\""; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Gets all properties", "array_size(sys_properties())"), new ExampleScript("Gets a single property", "sys_properties('java.specification.vendor')"), new ExampleScript("Gets a single property", "sys_properties('methodscript.preference.debug-mode')")}; } } @api public static class get_env extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args.length == 1) { return new CString(System.getenv(args[0].val()), t); } else { CArray ca = CArray.GetAssociativeArray(t); for(String key : System.getenv().keySet()) { ca.set(key, System.getenv(key)); } return ca; } } @Override public String getName() { return "get_env"; } @Override public Integer[] numArgs() { return new Integer[]{0, 1}; } @Override public String docs() { return "mixed {[variableName]} Returns the environment variable specified, if variableName is set. Otherwise, returns an associative array" + " of all the environment variables."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } } @api public static class set_env extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @SuppressWarnings({"BroadCatchBlock", "TooBroadCatch", "UseSpecificCatch"}) @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { //TODO: Make this more robust by having a local cache of the environment which we modify, and get_env returns from. Map<String, String> newenv = new HashMap<String, String>(System.getenv()); newenv.put(args[0].val(), args[1].val()); boolean ret; try { Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); ret = true; } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); for(Class cl : classes) { if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { Field field = cl.getDeclaredField("m"); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } ret = true; } catch (Exception e2) { ret = false; if(Prefs.DebugMode()) { CHLog.GetLogger().e(CHLog.Tags.GENERAL, e2, t); } } } catch (Exception e1) { ret = false; if(Prefs.DebugMode()) { CHLog.GetLogger().e(CHLog.Tags.GENERAL, e1, t); } } return CBoolean.get(ret); } @Override public String getName() { return "set_env"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {variableName, value} Sets the value of an environment variable. This only changes the environment value in this process, not system-wide." + " This uses some hackery to work, and may not be 100% reliable in all cases, and shouldn't be relied on heavily. It will" + " always work with get_env, however, so you can rely on that mechanism. The value will always be interpreted as a string, so if you are expecting" + " a particular data type on a call to get_env, you will need to manually cast the variable. Arrays will be toString'd as well, but will be accepted."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } } @api @noboilerplate @seealso(StringHandling.decrypt_secure_string.class) public static class prompt_pass extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!Static.InCmdLine(environment)) { throw new CREInsufficientPermissionException(getName() + " cannot be used outside of cmdline mode.", t); } boolean mask = true; if(args.length > 1) { mask = ArgumentValidation.getBoolean(args[1], t); } String prompt = args[0].val(); Character cha = new Character((char) 0); if(mask) { cha = new Character('*'); } jline.console.ConsoleReader reader = null; try { reader = new jline.console.ConsoleReader(); reader.setExpandEvents(false); return new CSecureString(reader.readLine(Static.MCToANSIColors(prompt), cha).toCharArray(), t); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } finally { if(reader != null) { reader.close(); } } } @Override public String getName() { return "prompt_pass"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "secure_string {prompt, [mask]} Prompts the user for a password. This only works in cmdline mode. If mask is true (default)," + " then the password displays * characters for each password character they type. If mask is false, the field" + " stays blank as they type. What they type is returned once they hit enter. The value returned is a secure_string," + " so to get the actual password, you must use decrypt_secure_string."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "prompt_pass('password: ');", "Would wait for the user to type in a password"), new ExampleScript("Decrypting the password", "@password = prompt_pass('password: ');\n" + "msg(@password);\n" + "msg(decrypt_secure_string(@password));", "password: ****\n**secure string**\n{p,a,s,s}") }; } } @api @noboilerplate public static class prompt_char extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { requireCmdlineMode(environment, this, t); String prompt = args[0].val(); try { char c = promptChar(Static.MCToANSIColors(prompt)); return new CString(c, t); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } } /** * Prompts for a single char from the console. The character typed is returned. * @param prompt * @return * @throws IOException */ public static char promptChar(String prompt) throws IOException { StreamUtils.GetSystemOut().print(prompt); StreamUtils.GetSystemOut().flush(); try(jline.console.ConsoleReader reader = new jline.console.ConsoleReader()) { reader.setExpandEvents(false); char c = (char) reader.readCharacter(); StreamUtils.GetSystemOut().println(c); return c; } } @Override public String getName() { return "prompt_char"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {prompt} Prompts the user for a single character. They do not need to hit enter first. This only works" + " in cmdline mode."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate public static class prompt_line extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!Static.InCmdLine(environment)) { throw new CREInsufficientPermissionException(getName() + " cannot be used outside of cmdline mode.", t); } String prompt = args[0].val(); jline.console.ConsoleReader reader = null; try { reader = new jline.console.ConsoleReader(); reader.setExpandEvents(false); String line = reader.readLine(Static.MCToANSIColors(prompt)); return new CString(line, t); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } finally { if(reader != null) { reader.close(); } } } @Override public String getName() { return "prompt_line"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "string {prompt} Prompts the user for a line. The line typed is returned once the user presses enter. This" + " only works in cmdline mode."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate public static class sys_beep extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREPluginInternalException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { java.awt.Toolkit.getDefaultToolkit().beep(); return CVoid.VOID; } @Override public String getName() { return "sys_beep"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "void {} Emits a system beep, on the system itself, not in game. This is only useful from cmdline."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate public static class clear_screen extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return null; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(Static.InCmdLine(environment)) { try { new jline.console.ConsoleReader().clearScreen(); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } } return CVoid.VOID; } @Override public String getName() { return "clear_screen"; } @Override public Integer[] numArgs() { return new Integer[]{0}; } @Override public String docs() { return "void {} Clears the screen. This only works from cmdline mode, nothing happens otherwise."; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate @seealso({shell.class, shell_on_adv.class, shell_on.class}) public static class shell_adv extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(final Target t, final Environment environment, Mixed... args) throws ConfigRuntimeException { if(!Static.InCmdLine(environment)) { if(!Prefs.AllowShellCommands()) { throw new CREInsufficientPermissionException("Shell commands are not allowed. Enable them in preferences.ini.", t); } if(environment.getEnv(GlobalEnv.class).GetDynamicScriptingMode() && !Prefs.AllowDynamicShell()) { throw new CREInsufficientPermissionException("Shell commands are disabled from dynamic sources.", t); } } String[] command; File workingDir = null; final CClosure stdout; final CClosure stderr; final CClosure exit; final boolean subshell; if(args[0] instanceof CArray) { CArray array = (CArray) args[0]; command = new String[(int) array.size()]; for(int i = 0; i < array.size(); i++) { command[i] = array.get(i, t).val(); } } else { command = StringUtils.ArgParser(args[0].val()).toArray(new String[0]); } if(args.length > 1) { CArray options = Static.getArray(args[1], t); if(options.containsKey("workingDir") && !(options.get("workingDir", t) instanceof CNull)) { workingDir = new File(options.get("workingDir", t).val()); if(!workingDir.isAbsolute()) { workingDir = new File(t.file().getParentFile(), workingDir.getPath()); } } stdout = (options.containsKey("stdout") && !(options.get("stdout", t) instanceof CNull) ? Static.getObject(options.get("stdout", t), t, CClosure.class) : null); stderr = (options.containsKey("stderr") && !(options.get("stderr", t) instanceof CNull) ? Static.getObject(options.get("stderr", t), t, CClosure.class) : null); exit = (options.containsKey("exit") && !(options.get("exit", t) instanceof CNull) ? Static.getObject(options.get("exit", t), t, CClosure.class) : null); subshell = (options.containsKey("subshell") ? ArgumentValidation.getBoolean(options.get("subshell", t), t) : false); } else { stdout = null; stderr = null; exit = null; subshell = false; } final CommandExecutor cmd = new CommandExecutor(command); cmd.setWorkingDir(workingDir); final MutableObject<StringBuilder> sbout = new MutableObject(new StringBuilder()); final MutableObject<StringBuilder> sberr = new MutableObject(new StringBuilder()); cmd.setSystemOut(new OutputStream() { @Override public void write(int b) throws IOException { if(stdout == null) { return; } char c = (char) b; if(c == '\n' || b == -1) { try { StaticLayer.GetConvertor().runOnMainThreadAndWait(new Callable<Object>() { @Override public Object call() throws Exception { stdout.execute(new CString(sbout.getObject(), t)); return null; } }); } catch (Exception ex) { Logger.getLogger(Cmdline.class.getName()).log(Level.SEVERE, null, ex); } sbout.setObject(new StringBuilder()); } else { sbout.getObject().append(c); } } }); cmd.setSystemErr(new OutputStream() { @Override public void write(int b) throws IOException { if(stderr == null) { return; } char c = (char) b; if(c == '\n' || b == -1) { try { StaticLayer.GetConvertor().runOnMainThreadAndWait(new Callable<Object>() { @Override public Object call() throws Exception { stderr.execute(new CString(sberr.getObject(), t)); return null; } }); } catch (Exception ex) { Logger.getLogger(Cmdline.class.getName()).log(Level.SEVERE, null, ex); } sberr.setObject(new StringBuilder()); } else { sberr.getObject().append(c); } } }); try { cmd.start(); } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } Runnable run = new Runnable() { @Override public void run() { environment.getEnv(GlobalEnv.class).GetDaemonManager().activateThread(null); try { final int exitCode = cmd.waitFor(); try { cmd.getSystemOut().flush(); if(cmd.getSystemOut() != StreamUtils.GetSystemOut()) { cmd.getSystemOut().close(); } } catch (IOException ex) { Logger.getLogger(Cmdline.class.getName()).log(Level.SEVERE, null, ex); } try { cmd.getSystemErr().flush(); if(cmd.getSystemErr() != StreamUtils.GetSystemErr()) { cmd.getSystemErr().close(); } } catch (IOException ex) { Logger.getLogger(Cmdline.class.getName()).log(Level.SEVERE, null, ex); } if(exit != null) { try { StaticLayer.GetConvertor().runOnMainThreadAndWait(new Callable<Object>() { @Override public Object call() throws Exception { exit.execute(new CInt(exitCode, t)); return null; } }); } catch (Exception ex) { Logger.getLogger(Cmdline.class.getName()).log(Level.SEVERE, null, ex); } } } catch (InterruptedException ex) { throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), t); } finally { environment.getEnv(GlobalEnv.class).GetDaemonManager().deactivateThread(null); } } }; if(subshell) { new Thread(run, "shell-adv-subshell (" + StringUtils.Join(command, " ") + ")").start(); } else { run.run(); } return CVoid.VOID; } @Override public String getName() { return "shell_adv"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "void {command, [options]} Runs a shell command. <code>command</code> can either be a string or an array of string arguments," + " which are run as an external process. Requires the allow-shell-commands option to be enabled in preferences, or run from command line, otherwise" + " an InsufficientPermissionException is thrown. ---- <code>options</code> is an associative array with zero or more" + " of the following options:\n\n" + "{| border=\"1\" class=\"wikitable\" cellspacing=\"1\" cellpadding=\"1\"\n" + "|-\n| workingDir || Sets the working directory for" + " the sub process. By default null, which represents the directory of this script." + " If the path is relative, it is relative to the directory of this script.\n" + "|-\n| stdout || A closure which receives the program" + " output to stdout line by line. The closure should accept a single string, which will be a line.\n" + "|-\n| stderr || A closure which receives the program output to stderr line by line. The closure should accept a single string," + " which should be a line.\n" + "|-\n| exit || A closure which is triggered one time, and contains the process's exit code, once it terminates.\n" + "|-\n| subshell || A boolean. If true, the process will not block, and script execution will continue. If false (default)" + " script execution will halt until the process exits.\n" + "|}"; } @Override public Version since() { return MSVersion.V3_3_1; } } @api @noboilerplate @seealso({shell_adv.class, shell_on.class, shell_adv.class}) public static class shell extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREShellException.class, CREIOException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!Static.InCmdLine(environment)) { if(!Prefs.AllowShellCommands()) { throw new CREInsufficientPermissionException("Shell commands are not allowed. Enable them in preferences.ini.", t); } if(environment.getEnv(GlobalEnv.class).GetDynamicScriptingMode() && !Prefs.AllowDynamicShell()) { throw new CREInsufficientPermissionException("Shell commands are disabled from dynamic sources.", t); } } String[] command; int expectedExitCode = 0; File workingDir = null; if(args[0] instanceof CArray) { CArray array = (CArray) args[0]; command = new String[(int) array.size()]; for(int i = 0; i < array.size(); i++) { command[i] = array.get(i, t).val(); } } else { command = StringUtils.ArgParser(args[0].val()).toArray(new String[0]); } if(args.length > 1) { CArray options = Static.getArray(args[1], t); if(options.containsKey("expectedExitCode")) { expectedExitCode = Static.getInt32(options.get("expectedExitCode", t), t); } if(options.containsKey("workingDir") && !(options.get("workingDir", t) instanceof CNull)) { workingDir = new File(options.get("workingDir", t).val()); if(!workingDir.isAbsolute()) { workingDir = new File(t.file().getParentFile(), workingDir.getPath()); } } } CommandExecutor cmd = new CommandExecutor(command); final StringBuilder sout = new StringBuilder(); OutputStream out = new BufferedOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { sout.append((char) b); } }); final StringBuilder serr = new StringBuilder(); OutputStream err = new BufferedOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { serr.append((char) b); } }); cmd.setSystemOut(out).setSystemErr(err).setWorkingDir(workingDir); try { int exitCode = cmd.start().waitFor(); try { if(exitCode != expectedExitCode) { err.flush(); throw new CREShellException(serr.toString(), t); } else { out.flush(); return new CString(sout.toString(), t); } } finally { out.close(); err.close(); } } catch (IOException ex) { throw new CREIOException(ex.getMessage(), t); } catch (InterruptedException ex) { throw ConfigRuntimeException.CreateUncatchableException(ex.getMessage(), t); } } @Override public String getName() { return "shell"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "string {command, [options]} Runs a shell command. <code>command</code> can be either a string, or array of string" + " arguments. This works mostly like {{function|shell_adv}} however, it buffers then" + " returns the output for sysout once the process is completed, and throws a ShellException with the exception" + " message set to the syserr output if the" + " process exits with an exit code that isn't the expectedExitCode, which defaults to 0. This is useful for simple commands" + " that return output and don't need very complicated usage, and failures don't need to check the exact error code." + " If the underlying command throws an IOException, it is" + " passed through. Requires the allow-shell-commands option to be enabled in preferences, or run from command line, otherwise" + " an InsufficientPermissionException is thrown. Options is an associative array which expects zero or more" + " of the following options: expectedErrorCode - The expected error code indicating successful command completion. Defaults to 0." + " workingDir - Sets the working directory for the sub process. By default null, which represents the directory of this script." + " If the path is relative, it is relative to the directory of this script."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public com.laytonsmith.core.functions.ExampleScript[] examples() throws com.laytonsmith.core.exceptions.ConfigCompileException { return new com.laytonsmith.core.functions.ExampleScript[]{ new com.laytonsmith.core.functions.ExampleScript("Basic usage with array", "shell(array('grep', '-r', 'search content', '*'))", "<output of command>"), new com.laytonsmith.core.functions.ExampleScript("Basic usage with string", "shell('grep -r \"search content\" *')", "<output of command>"), new com.laytonsmith.core.functions.ExampleScript("Changing the working directory", "shell('grep -r \"search content\" *', array(workingDir: '/'))", "<output of command>")}; } } @api @noboilerplate @seealso({shell_adv.class, shell_on.class, shell.class, get_os.class}) public static class shell_on_adv extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREShellException.class, CREIOException.class, CREFormatException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { Set<OSUtils.OS> oses = new HashSet<>(); String osS = args[0].val(); for(String osSS : osS.split("\\|")) { OSUtils.OS os; try { os = OSUtils.OS.valueOf(osSS); } catch (IllegalArgumentException ex) { throw new CREFormatException("Input OS must be one of " + StringUtils.Join(OSUtils.OS.values(), ", ", ", or "), t, ex); } oses.add(os); } if(oses.contains(OSUtils.GetOS())) { return new shell_adv().exec(t, environment, ArrayUtils.cast(ArrayUtils.slice(args, 1, args.length - 1), Construct[].class)); } return CVoid.VOID; } @Override public String getName() { return "shell_on_adv"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "void {os, command, [options]} Executes the command if and only if on the given operating system (one of " + StringUtils.Join(OSUtils.OS.values(), ", ", ", or ") + "). If not on the specified OS, this command does nothing. The os argument may be a pipe seperated list of OSes, for instance 'MAC|LINUX', which is" + " useful given that both are unix based, and often times the same command will work for both." + " Otherwise completely equivalent to {{function|shell_adv}}. This is useful, because usually a command is" + " tailored to a specific OS, and simply won't run on other OSes. This allows you to create similar commands across various OSes, and ensure that they only" + " run for the correct OS."; } @Override public Version since() { return MSVersion.V3_3_2; } } @api @noboilerplate @seealso({shell.class, shell_adv.class, shell_on_adv.class, get_os.class}) public static class shell_on extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientPermissionException.class, CREShellException.class, CREIOException.class, CREFormatException.class}; } @Override public boolean isRestricted() { return true; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { Set<OSUtils.OS> oses = new HashSet<>(); String osS = args[0].val(); for(String osSS : osS.split("\\|")) { OSUtils.OS os; try { os = OSUtils.OS.valueOf(osSS); } catch (IllegalArgumentException ex) { throw new CREFormatException("Input OS must be one of " + StringUtils.Join(OSUtils.OS.values(), ", ", ", or "), t, ex); } oses.add(os); } if(oses.contains(OSUtils.GetOS())) { return new shell().exec(t, environment, ArrayUtils.cast(ArrayUtils.slice(args, 1, args.length - 1), Construct[].class)); } return CNull.NULL; } @Override public String getName() { return "shell_on"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "string {os, command, [options]} Executes the command if and only if on the given operating system (one of " + StringUtils.Join(OSUtils.OS.values(), ", ", ", or ") + "). If not on the specified OS, this command returns null. The os argument may be a pipe seperated list of OSes, for instance 'MAC|LINUX', which is" + " useful given that both are unix based, and often times the same command will work for both." + " Otherwise completely equivalent to {{function|shell}}. This is useful, because usually a command is" + " tailored to a specific OS, and simply won't run on other OSes. This allows you to create similar commands across various OSes, and ensure that they only" + " run for the correct OS."; } @Override public Version since() { return MSVersion.V3_3_2; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ /** * Requires cmdline mode. If not currently in cmdline mode, a proper CRE is thrown. * * @param environment * @param f The function this is being called from. * @param t * @throws ConfigRuntimeException If not in cmdline mode. */ public static void requireCmdlineMode(Environment environment, Function f, Target t) throws ConfigRuntimeException { if(!Static.InCmdLine(environment)) { throw new CREInsufficientPermissionException(f.getName() + " cannot be used outside of cmdline mode.", t); } } }
package com.manning.hip.ch11; import com.maxmind.geoip.LookupService; import org.apache.pig.EvalFunc; import org.apache.pig.FuncSpec; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * a = load '1.txt'; * DEFINE GeoIP com.manning.hip.ch11.TypedCommonLogLoader("/tmp/GeoIP.dat"); * b = foreach a generate GeoIP(*); * dump b; */ public class PigGeolocationUDF extends EvalFunc<String> { private LookupService geoloc; private static final String COUNTRY = "country"; private final static String DIST_CACHE_GEOIP_NAME = "geoip"; public String exec(Tuple input) throws IOException { if (input == null || input.size() == 0) { return null; } Object object = input.get(0); if (object == null) { return null; } String ip = (String) object; return lookup(ip); } protected String lookup(String ip) throws IOException { if (geoloc == null) { geoloc = new LookupService("./" + DIST_CACHE_GEOIP_NAME, LookupService.GEOIP_MEMORY_CACHE); } String country = geoloc.getCountry(ip).getName(); if ("N/A".equals(country)) { return null; } return country; } @Override public List<FuncSpec> getArgToFuncMapping() throws FrontendException { List<FuncSpec> funcList = new ArrayList<FuncSpec>(); funcList.add(new FuncSpec(this.getClass().getName(), new Schema(new Schema.FieldSchema(null, DataType.CHARARRAY)))); funcList.add(new FuncSpec(PigLongGeolocationUDF.class.getName(), new Schema(new Schema.FieldSchema(null, DataType.LONG)))); return funcList; } @Override public Schema outputSchema(Schema input) { return new Schema( new Schema.FieldSchema(COUNTRY, DataType.CHARARRAY)); } }
package com.metacodestudio.hotsuploader; import com.metacodestudio.hotsuploader.files.FileHandler; import com.metacodestudio.hotsuploader.utils.SimpleHttpClient; import com.metacodestudio.hotsuploader.utils.StormHandler; import com.metacodestudio.hotsuploader.versions.ReleaseManager; import com.metacodestudio.hotsuploader.window.HomeController; import io.datafx.controller.flow.Flow; import io.datafx.controller.flow.FlowHandler; import io.datafx.controller.flow.container.DefaultFlowContainer; import io.datafx.controller.flow.context.ViewFlowContext; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.net.URL; public class Client extends Application { public static void main(String[] args) { Application.launch(Client.class, args); } @Override public void start(final Stage primaryStage) throws Exception { ClassLoader loader = ClassLoader.getSystemClassLoader(); URL logo = loader.getResource("images/logo-desktop.png"); assert logo != null; Image image = new Image(logo.toString()); primaryStage.getIcons().add(image); primaryStage.setResizable(false); primaryStage.setTitle("HotSLogs UploaderFX"); StormHandler stormHandler = new StormHandler(); addToTray(logo, primaryStage); Flow flow = new Flow(HomeController.class); FlowHandler flowHandler = flow.createHandler(new ViewFlowContext()); ViewFlowContext flowContext = flowHandler.getFlowContext(); SimpleHttpClient httpClient = new SimpleHttpClient(); ReleaseManager releaseManager = new ReleaseManager(httpClient); registerInContext(flowContext, stormHandler, releaseManager, setupFileHandler(stormHandler), httpClient); DefaultFlowContainer container = new DefaultFlowContainer(); releaseManager.verifyLocalVersion(stormHandler); StackPane pane = flowHandler.start(container); primaryStage.setScene(new Scene(pane)); primaryStage.show(); } private FileHandler setupFileHandler(final StormHandler stormHandler) throws IOException { FileHandler fileHandler = new FileHandler(stormHandler); fileHandler.cleanup(); fileHandler.registerInitial(); return fileHandler; } private void registerInContext(ViewFlowContext context, Object... itemsToAdd) { for (final Object itemToAdd : itemsToAdd) { context.register(itemToAdd); } } private void addToTray(final URL imageURL, final Stage primaryStage) { // TODO FIND A WAY TO MAKE THIS SWEET ON OSX boolean support = SystemTray.isSupported() && StormHandler.isWindows(); if (support) { final SystemTray tray = SystemTray.getSystemTray(); final java.awt.Image image = Toolkit.getDefaultToolkit().getImage(imageURL); final PopupMenu popup = new PopupMenu(); final MenuItem showItem = new MenuItem("Show"); final MenuItem exitItem = new MenuItem("Exit"); // Deal with window events Platform.setImplicitExit(false); primaryStage.setOnHiding(value -> { primaryStage.hide(); value.consume(); }); // Declare shared action for showItem and trayicon click Runnable openAction = () -> Platform.runLater(() -> { primaryStage.show(); primaryStage.toFront(); }); popup.add(showItem); popup.add(exitItem); final TrayIcon trayIcon = new TrayIcon(image, StormHandler.getApplicationName(), popup); trayIcon.setImageAutoSize(true); // Add listeners trayIcon.addMouseListener(mouseListener(openAction)); showItem.addActionListener(e -> openAction.run()); exitItem.addActionListener(event -> { Platform.exit(); System.exit(0); }); try { tray.add(trayIcon); } catch (AWTException e) { e.printStackTrace(); } } else { primaryStage.setOnCloseRequest(event -> System.exit(0)); } } private MouseListener mouseListener(final Runnable result) { return new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { result.run(); } } @Override public void mousePressed(final MouseEvent e) { } @Override public void mouseReleased(final MouseEvent e) { } @Override public void mouseEntered(final MouseEvent e) { } @Override public void mouseExited(final MouseEvent e) { } }; } }
package com.payu.sdk.model.request; /** * Represents the environment in the PayU SDK. * * @author PayU Latam * @since 1.0.0 * @version 1.0.0, 21/08/2013 */ public enum Environment { /** * Default url for payments and reports requests */ API_URL("https://api.payulatam.com/payments-api/", "https://api.payulatam.com/reports-api/"); /** Payments request's url */ private String paymentsUrl; /** Reports request's url */ private String reportsUrl; /** * Private constructor * * @param paymentsUrl * the payments url to use * @param reportsUrl * the reports url to use */ private Environment(String paymentsUrl, String reportsUrl) { this.paymentsUrl = paymentsUrl; this.reportsUrl = reportsUrl; } /** * Creates an environment with the given urls * * @param paymentsUrl * the payments url to use * @param reportsUrl * the reports url to use * @return The created environment */ public static Environment createEnvironment(String paymentsUrl, String reportsUrl) { Environment environment = Environment.API_URL; environment.paymentsUrl = paymentsUrl; environment.reportsUrl = reportsUrl; return environment; } /** * Returns the payments url * * @return the payments url */ public String getPaymentsUrl() { return paymentsUrl; } /** * Returns the reports url * * @return the reports Url */ public String getReportsUrl() { return reportsUrl; } }
package com.rultor.agents.github.qtn; import com.google.common.collect.ImmutableMap; import com.jcabi.aspects.Immutable; import com.jcabi.github.Comment; import com.jcabi.github.Issue; import com.jcabi.log.Logger; import com.rultor.agents.github.Answer; import com.rultor.agents.github.Question; import com.rultor.agents.github.Req; import java.io.IOException; import java.net.URI; import java.util.ResourceBundle; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Release request. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.3.6 * @checkstyle MultipleStringLiteralsCheck (500 lines) */ @Immutable @ToString @EqualsAndHashCode public final class QnRelease implements Question { /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); @Override public Req understand(final Comment.Smart comment, final URI home) throws IOException { new Answer(comment).post( String.format( QnRelease.PHRASES.getString("QnRelease.start"), home.toASCIIString() ) ); final Issue issue = comment.issue(); Logger.info( this, "release request found in %s#%d, comment #%d", issue.repo().coordinates(), issue.number(), comment.number() ); return new Req.Simple( "release", new ImmutableMap.Builder<String, String>() .put("head_branch", "master") .put( "head", String.format( "git@github.com:%s.git", comment.issue().repo().coordinates() ) ) .build() ); } }
package com.sandwell.JavaSimulation; import com.jaamsim.controllers.RenderManager; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.InputAgent; import com.jaamsim.input.ValueInput; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.Clock; import com.sandwell.JavaSimulation3D.GUIFrame; /** * Class Simulation - Sandwell Discrete Event Simulation * <p> * Class structure defining essential simulation objects. Eventmanager is * instantiated to manage events generated in the simulation. Function prototypes * are defined which any simulation must define in order to run. */ public class Simulation extends Entity { @Keyword(description = "The initialization period for the simulation run. The model will " + "run for the initialization period and then clear the statistics " + "and execute for the specified run duration. The total length of the " + "simulation run will be the sum of Initialization and Duration.", example = "Simulation Initialization { 720 h }") protected final DoubleInput initializationTime; @Keyword(description = "Date at which the simulation run is started (yyyy-mm-dd). This " + "input has no effect on the simulation results unless the seasonality " + "factors vary from month to month.", example = "Simulation StartDate { 2011-01-01 }") protected final StringInput startDate; @Keyword(description = "Time at which the simulation run is started (hh:mm).", example = "Simulation StartTime { 2160 h }") private final ValueInput startTimeInput; @Keyword(description = "The duration of the simulation run in which all statistics will be recorded.", example = "Simulation Duration { 8760 h }") protected final DoubleInput runDuration; @Keyword(description = "The number of discrete time units in one hour.", example = "Simulation SimulationTimeScale { 4500 }") private final DoubleInput simTimeScaleInput; @Keyword(description = "If the value is TRUE, then the input report file will be printed after loading the " + "configuration file. The input report can always be generated when needed by selecting " + "\"Print Input Report\" under the File menu.", example = "Simulation PrintInputReport { TRUE }") private final BooleanInput printInputReport; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput traceEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput verifyEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private final BooleanInput exitAtStop; @Keyword(description = "The real time speed up factor", example = "RunControl RealTimeFactor { 1200 }") private final IntegerInput realTimeFactor; public static final int DEFAULT_REAL_TIME_FACTOR = 10000; public static final int MIN_REAL_TIME_FACTOR = 1; public static final int MAX_REAL_TIME_FACTOR= 1000000; @Keyword(description = "A Boolean to turn on or off real time in the simulation run", example = "RunControl RealTime { TRUE }") private final BooleanInput realTime; protected double startTime; protected double endTime; private static String modelName = "JaamSim"; { runDuration = new DoubleInput( "Duration", "Key Inputs", 8760.0 ); runDuration.setValidRange( 1e-15d, Double.POSITIVE_INFINITY ); runDuration.setUnits( "h" ); this.addInput( runDuration, true, "RunDuration" ); initializationTime = new DoubleInput( "Initialization", "Key Inputs", 0.0 ); initializationTime.setValidRange( 0.0d, Double.POSITIVE_INFINITY ); initializationTime.setUnits( "h" ); this.addInput( initializationTime, true, "InitializationDuration" ); startDate = new StringInput("StartDate", "Key Inputs", null); this.addInput(startDate, true); startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d); startTimeInput.setUnitType(TimeUnit.class); startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY); this.addInput(startTimeInput, true); exitAtStop = new BooleanInput( "ExitAtStop", "Key Inputs", false ); this.addInput( exitAtStop, true ); simTimeScaleInput = new DoubleInput( "SimulationTimeScale", "Key Inputs", 4000.0d ); simTimeScaleInput.setValidRange( 1e-15d, Double.POSITIVE_INFINITY ); this.addInput( simTimeScaleInput, true ); traceEventsInput = new BooleanInput( "TraceEvents", "Key Inputs", false ); this.addInput( traceEventsInput, false ); verifyEventsInput = new BooleanInput( "VerifyEvents", "Key Inputs", false ); this.addInput( verifyEventsInput, false ); printInputReport = new BooleanInput( "PrintInputReport", "Key Inputs", false ); this.addInput( printInputReport, true ); realTimeFactor = new IntegerInput("RealTimeFactor", "Key Inputs", DEFAULT_REAL_TIME_FACTOR); realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR); this.addInput(realTimeFactor, true); realTime = new BooleanInput("RealTime", "Key Inputs", false); this.addInput(realTime, true); } /** * Constructor for the Simulation * Protected makes this a 'singleton' class -- only one instance of it exists. is instantiated through 'getSimulation()' method. */ public Simulation() { // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; } @Override public void validate() { super.validate(); if( startDate.getValue() != null && !Tester.isDate( startDate.getValue() ) ) { throw new InputErrorException("The value for Start Date must be a valid date."); } } @Override public void earlyInit() { super.earlyInit(); Process.setSimTimeScale(simTimeScaleInput.getValue()); if( startDate.getValue() != null ) { Clock.getStartingDateFromString( startDate.getValue() ); } double startTimeHours = startTimeInput.getValue() / 3600.0d; startTime = Clock.calcTimeForYear_Month_Day_Hour(1, Clock.getStartingMonth(), Clock.getStartingDay(), startTimeHours); endTime = this.getStartTime() + this.getInitializationTime() + this.getRunDuration(); } private static class EndAtTarget extends ProcessTarget { final Simulation sim; EndAtTarget(Simulation sim) { this.sim = sim; } @Override public String getDescription() { return sim.getInputName() + ".doEndAt"; } @Override public void process() { sim.doEndAt(sim.getEndTime()); } } @Override public void startUp() { super.startUp(); Process.start(new EndAtTarget(this)); } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if(in == realTimeFactor || in == realTime) { EventManager.rootManager.setExecuteRealTime(realTime.getValue(), realTimeFactor.getValue()); GUIFrame.instance().updateForRealTime(this.getRealTimeExecution(), this.getRealTimeFactor()); return; } if (in == printInputReport) { InputAgent.setPrintInputs(printInputReport.getValue()); return; } } public void clear() { EventManager.rootManager.basicInit(); this.resetInputs(); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; // close warning/error trace file InputAgent.closeLogFile(); FrameBox.clear(); EntityPallet.clear(); RenderManager.clear(); // Kill all entities except simulation while(Entity.getAll().size() > 1) { Entity ent = Entity.getAll().get(Entity.getAll().size()-1); ent.kill(); } GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_LOADED); } /** * Initializes and starts the model * 1) Initializes EventManager to accept events. * 2) calls startModel() to allow the model to add its starting events to EventManager * 3) start EventManager processing events */ public void start() { EventManager.rootManager.basicInit(); if( traceEventsInput.getValue() ) { EventTracer.traceAllEvents(traceEventsInput.getValue()); } else if( verifyEventsInput.getValue() ) { EventTracer.verifyAllEvents(verifyEventsInput.getValue()); } // Validate each entity based on inputs only for (int i = 0; i < Entity.getAll().size(); i++) { try { Entity.getAll().get(i).validate(); } catch (Throwable e) { InputAgent.doError(e); ExceptionBox.instance().setInputError(Entity.getAll().get(i), e); return; } } EventManager.rootManager.scheduleProcess(0, EventManager.PRIO_DEFAULT, new StartModelTarget(this)); Simulation.resume(); } public static final void resume() { EventManager.rootManager.resume(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_RUNNING); } /** * Requests the EventManager to stop processing events. */ public static final void pause() { EventManager.rootManager.pause(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_PAUSED); } /** * Requests the EventManager to stop processing events. */ public static final void stop() { EventManager.rootManager.pause(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_STOPPED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } private static class StartUpTarget extends ProcessTarget { final Entity ent; StartUpTarget(Entity ent) { this.ent = ent; } @Override public String getDescription() { return ent.getInputName() + ".startUp"; } @Override public void process() { ent.startUp(); } } private static class StartModelTarget extends ProcessTarget { final Simulation ent; StartModelTarget(Simulation sim) { this.ent = sim; } @Override public String getDescription() { return ent.getInputName() + ".startModel"; } @Override public void process() { ent.startModel(); } } /** * Called by Simulation to inform the model to begin simulation networks. Events should not be * added to the EventManager before startModel(); **/ public void startModel() { for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).earlyInit(); } if( this.getStartTime() > 0.0 ) { scheduleWait( this.getStartTime() ); } // Initialize each entity based on early initialization and start networks for (int i = 0; i < Entity.getAll().size(); i++) { Process.start(new StartUpTarget(Entity.getAll().get(i))); } } /** * Called at the end of the run */ public void doEndAt( double end ) { if( (end - getCurrentTime()) > 0.0 ) { scheduleWait( (end - getCurrentTime()) ); Simulation.pause(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).doEnd(); } System.out.println( "Made it to do end at" ); // close warning/error trace file InputAgent.closeLogFile(); if( this.getExitAtStop() ) { GUIFrame.shutdown(0); } Simulation.pause(); } } /** * Returns the end time of the run. * @return double - the time the current run will stop */ public double getEndTime() { return endTime; } /** * Return the run duration for the run (not including intialization) */ public double getRunDuration() { return runDuration.getValue(); } /** * Returns the start time of the run. */ public double getStartTime() { return startTime; } /** * Return the initialization duration in hours */ public double getInitializationTime() { return initializationTime.getValue(); } /** returns whether the simulation is currently executing in real time execution mode */ public boolean getRealTimeExecution() { return realTime.getValue(); } /** retrieves the current value for speedup factor for real time execution mode */ public int getRealTimeFactor() { return realTimeFactor.getValue(); } public static void setModelName(String newModelName) { modelName = newModelName; } public static String getModelName() { return modelName; } public boolean getExitAtStop() { if (InputAgent.getBatch()) return true; return exitAtStop.getValue(); } }
package com.sandwell.JavaSimulation; import com.jaamsim.input.Output; import com.jaamsim.input.UnitTypeInput; import com.jaamsim.input.ValueInput; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; public class TimeSeries extends Entity implements TimeSeriesProvider { @Keyword(description = "A list of time series records with default format { 'yyyy MM dd HH:mm' value units }, where\n" + "yyyy is the year\n" + "MM is the month (1-12)\n" + "dd is the day of the month\n" + "HH is the hour of day (0-23)\n" + "mm is the minutes (0-59)\n" + "value is the time series value for the given date and time\n" + "units is the optional units for the value\n" + "The date and times must be given in increasing order.", example = "TimeSeries1 Value { { '2010 1 1 0:00' 0.5 m } { '2010 1 1 3:00' 1.5 m } { '2010 1 1 6:00' 1.2 m } }") private final TimeSeriesDataInput value; @Keyword(description = "The unit type for the time series (e.g. DistanceUnit, TimeUnit, MassUnit). " + "If the UnitType keyword is specified, it must be specified before the Value keyword.", example = "TimeSeries1 UnitType { DistanceUnit }") private final UnitTypeInput unitType; @Keyword(description = "The format for the date and time (e.g. 'yyyy-MM-dd HH:mm:ss', yyyy/MM/dd). " + "Put single quotes around the format if it includes spaces.", example = "TimeSeries1 DateFormat { 'yyyy-MM-dd HH:mm' }") private final StringInput dateFormat; @Keyword(description = "Defines when the time series will repeat from the start.", example = "TimeSeries1 CycleTime { 8760.0 h }") private final ValueInput cycleTime; private int indexOfCurrentTime; // The index of the time in the last call to getValueForTime() { value = new TimeSeriesDataInput("Value", "Key Inputs", null); value.setUnitType(UserSpecifiedUnit.class); this.addInput(value, true); unitType = new UnitTypeInput( "UnitType", "Key Inputs" ); this.addInput( unitType, true ); dateFormat = new StringInput("DateFormat", "Key Inputs", null); this.addInput(dateFormat, true); cycleTime = new ValueInput( "CycleTime", "Key Inputs", Double.POSITIVE_INFINITY ); cycleTime.setUnitType(TimeUnit.class); this.addInput( cycleTime, true ); } public TimeSeries() { } @Override public void validate() { super.validate(); if( unitType.getValue() == null ) throw new InputErrorException( "UnitType must be specified first" ); if( value.getValue() == null || value.getValue().getTimeList().size() == 0 ) throw new InputErrorException( "Time series Value must be specified" ); if( this.getCycleTimeInHours() < value.getValue().getTimeList().get( value.getValue().getTimeList().size() -1 ) ) throw new InputErrorException( "CycleTime must be larger than the last time in the series" ); } @Override public void earlyInit() { super.earlyInit(); indexOfCurrentTime = 0; } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if (in == unitType) { value.setUnitType( unitType.getUnitType() ); return; } if ( in == dateFormat ) { try { value.setDateFormat( dateFormat.getValue() ); } catch ( IllegalArgumentException e ) { throw new InputErrorException( "Invalid date format " + dateFormat.getValue() ); } } } @Output( name="PresentValue", description="The time series value for the present time." ) public double getPresentValue( double simTime ) { return this.getValueForTime( simTime / 3600.0 ); } /** * Return the value for the given simulation time in hours */ @Override public double getValueForTime( double time ) { DoubleVector timeList = this.getTimeList(); DoubleVector valueList = this.getValueList(); // Update the index within the series for the current time indexOfCurrentTime = this.getIndexForTime(getCurrentTime(), indexOfCurrentTime); // Determine the time in the cycle for the given time double timeInCycle; if( this.getCycleTimeInHours() == Double.POSITIVE_INFINITY ) { timeInCycle = time; } else { int completedCycles = (int)Math.floor( time / this.getCycleTimeInHours() ); timeInCycle = time - ( completedCycles * this.getCycleTimeInHours() ); } // Perform linear search for time from indexOfTime for( int i = indexOfCurrentTime; i < timeList.size()-1; i++ ) { if( Tester.lessOrEqualCheckTimeStep( timeList.get( i ), timeInCycle ) && Tester.lessCheckTimeStep( timeInCycle, timeList.get( i+1 ) ) ) { return valueList.get( i ); } } // If the time in the cycle is greater than the last time, return the last value if( Tester.greaterOrEqualCheckTimeStep( timeInCycle, timeList.get( timeList.size() - 1 ) ) ) { return valueList.get( valueList.size() - 1 ); } // Perform linear search for time from 0 for( int i = 0; i < indexOfCurrentTime; i++ ) { if( Tester.lessOrEqualCheckTimeStep( timeList.get( i ), timeInCycle ) && Tester.lessCheckTimeStep( timeInCycle, timeList.get( i+1 ) ) ) { return valueList.get( i ); } } // No value was found for time, return 0 return 0.0; } /** * Return the index for the given simulation time in hours */ public int getIndexForTime( double time, int startIndex ) { DoubleVector timeList = value.getValue().getTimeList(); // Determine the time in the cycle for the given time double timeInCycle; if( this.getCycleTimeInHours() == Double.POSITIVE_INFINITY ) { timeInCycle = time; } else { int completedCycles = (int)Math.floor( time / this.getCycleTimeInHours() ); timeInCycle = time - ( completedCycles * this.getCycleTimeInHours() ); } // Perform linear search for time from startIndex for( int i = startIndex; i < timeList.size()-1; i++ ) { if( Tester.lessOrEqualCheckTimeStep( timeList.get( i ), timeInCycle ) && Tester.lessCheckTimeStep( timeInCycle, timeList.get( i+1 ) ) ) { return i; } } // If the time in the cycle is greater than the last time, return the last value if( Tester.greaterOrEqualCheckTimeStep( timeInCycle, timeList.get( timeList.size() - 1 ) ) ) { return timeList.size() - 1; } // Perform linear search for time from 0 for( int i = 0; i < startIndex; i++ ) { if( Tester.lessOrEqualCheckTimeStep( timeList.get( i ), timeInCycle ) && Tester.lessCheckTimeStep( timeInCycle, timeList.get( i+1 ) ) ) { return i; } } // No value was found for time this.error( "getIndexForTime( "+time+", "+startIndex+" )", "No record was found for the given time.", "" ); return -1; } /** * Return the first time that the value will be updated, after the given time. */ @Override public double getNextChangeTimeAfter( double time ) { // Collect parameters for the current time int startIndex = this.getIndexForTime(time,indexOfCurrentTime)+1; double cycleTime = this.getCycleTimeInHours(); // Determine how many cycles through the time series have been completed int completedCycles = (int)Math.floor( time / cycleTime ); // If this is the last point in the cycle, need to cycle around to get the next point if( startIndex > this.getTimeList().size() - 1 ) { // If the series does not cycle, the value will never change if( cycleTime == Double.POSITIVE_INFINITY ) { return Double.POSITIVE_INFINITY; } else { double cycleOffset = 0.0; if( cycleTime != Double.POSITIVE_INFINITY ) { cycleOffset = (completedCycles+1)*cycleTime; } return this.getTimeList().get(0) + cycleOffset; } } // No cycling required, return the next value double cycleOffset = 0.0; if( cycleTime != Double.POSITIVE_INFINITY ) { cycleOffset = (completedCycles)*cycleTime; } return this.getTimeList().get(startIndex) + cycleOffset; } public DoubleVector getTimeList() { return value.getValue().getTimeList(); } public DoubleVector getValueList() { return value.getValue().getValueList(); } public double getCycleTimeInHours() { return cycleTime.getValue() / 3600; } @Override public double getMaxTimeValueInHours() { if( this.getCycleTimeInHours() != Double.POSITIVE_INFINITY ) return this.getCycleTimeInHours(); return this.getTimeList().get( this.getTimeList().size()-1 ); } /** * Return the time in hours from the given start time * until the value is less than or equal to the given limit. */ public double calcTimeFrom_UntilLessThanOrEqualTo( double time, double limit ) { // If the value at the start time is less than or equal to the limit, return 0 if( getValueForTime( time ) <= limit ) return 0; DoubleVector timeList = this.getTimeList(); DoubleVector valueList = this.getValueList(); // Determine the time in the cycle for the given time double timeInCycle; if( this.getCycleTimeInHours() == Double.POSITIVE_INFINITY ) { timeInCycle = time; } else { int completedCycles = (int)Math.floor( time / this.getCycleTimeInHours() ); timeInCycle = time - ( completedCycles * this.getCycleTimeInHours() ); } // Assume indexOfTime corresponds to the given start time // Perform linear search for time from indexOfTime + 1 for( int i = indexOfCurrentTime + 1; i < timeList.size(); i++ ) { if( valueList.get( i ) <= limit ) { return timeList.get( i ) - timeInCycle; } } // Perform linear search for time from 0 for( int i = 0; i < indexOfCurrentTime; i++ ) { if( valueList.get( i ) <= limit ) { return timeList.get( i ) + this.getCycleTimeInHours() - timeInCycle; } } // The value is never less than or equal to the limit. Return infinity return Double.POSITIVE_INFINITY; } /** * Return the time in hours from the given start time * until the value is greater than the given limit. */ public double calcTimeFrom_UntilGreaterThan( double time, double limit ) { // If the value at the start time greater the limit, return 0 if( getValueForTime( time ) > limit ) return 0; DoubleVector timeList = this.getTimeList(); DoubleVector valueList = this.getValueList(); // Determine the time in the cycle for the given time double timeInCycle; if( this.getCycleTimeInHours() == Double.POSITIVE_INFINITY ) { timeInCycle = time; } else { int completedCycles = (int)Math.floor( time / this.getCycleTimeInHours() ); timeInCycle = time - ( completedCycles * this.getCycleTimeInHours() ); } // Assume indexOfTime corresponds to the given start time // Perform linear search for time from indexOfTime + 1 for( int i = indexOfCurrentTime + 1; i < timeList.size(); i++ ) { if( valueList.get( i ) > limit ) { return timeList.get( i ) - timeInCycle; } } // Perform linear search for time from 0 for( int i = 0; i < indexOfCurrentTime; i++ ) { if( valueList.get( i ) > limit ) { return timeList.get( i ) + this.getCycleTimeInHours() - timeInCycle; } } // The value is never greater than the limit. Return infinity return Double.POSITIVE_INFINITY; } @Override public Class<? extends Unit> getUnitType() { return unitType.getUnitType(); } @Override public double getMaxValue() { return value.getValue().getMaxValue(); } public double getMinValue() { return value.getValue().getMinValue(); } }
package com.stripe.model; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.stripe.net.APIResource; public class EventDataDeserializer implements JsonDeserializer<EventData> { @SuppressWarnings("rawtypes") static Map<String, Class> objectMap = new HashMap<String, Class>(); static { objectMap.put("account", Account.class); objectMap.put("charge", Charge.class); objectMap.put("discount", Discount.class); objectMap.put("customer", Customer.class); objectMap.put("invoice", Invoice.class); objectMap.put("invoiceitem", InvoiceItem.class); objectMap.put("plan", Plan.class); objectMap.put("subscription", Subscription.class); objectMap.put("token", Token.class); objectMap.put("coupon", Coupon.class); objectMap.put("transfer", Transfer.class); objectMap.put("dispute", Dispute.class); objectMap.put("recipient", Recipient.class); objectMap.put("summary", Summary.class); objectMap.put("fee", Fee.class); objectMap.put("bank_account", BankAccount.class); objectMap.put("balance", Balance.class); objectMap.put("card", Card.class); } private Object deserializeJsonPrimitive(JsonPrimitive element) { if (element.isBoolean()) { return element.getAsBoolean(); } else if (element.isNumber()) { return element.getAsNumber(); } else { return element.getAsString(); } } private Object[] deserializeJsonArray(JsonArray arr) { Object[] elems = new Object[arr.size()]; Iterator<JsonElement> elemIter = arr.iterator(); int i = 0; while (elemIter.hasNext()) { JsonElement elem = elemIter.next(); elems[i++] = deserializeJsonElement(elem); } return elems; } private Object deserializeJsonElement(JsonElement element) { if (element.isJsonNull()) { return null; } else if (element.isJsonObject()) { Map<String, Object> valueMap = new HashMap<String, Object>(); populateMapFromJSONObject(valueMap, element.getAsJsonObject()); return valueMap; } else if (element.isJsonPrimitive()) { return deserializeJsonPrimitive(element.getAsJsonPrimitive()); } else if (element.isJsonArray()) { return deserializeJsonArray(element.getAsJsonArray()); } else { System.err.println("Unknown JSON element type for element " + element + ". " + "If you're seeing this messaage, it's probably a bug in the Stripe Java " + "library. Please contact us by email at support@stripe.com."); return null; } } private void populateMapFromJSONObject(Map<String, Object> objMap, JsonObject jsonObject) { for(Map.Entry<String, JsonElement> entry: jsonObject.entrySet()) { String key = entry.getKey(); JsonElement element = entry.getValue(); objMap.put(key, deserializeJsonElement(element)); } } @SuppressWarnings("unchecked") public EventData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { EventData eventData = new EventData(); JsonObject jsonObject = json.getAsJsonObject(); for(Map.Entry<String, JsonElement> entry: jsonObject.entrySet()) { String key = entry.getKey(); JsonElement element = entry.getValue(); if("previous_attributes".equals(key)) { Map<String, Object> previousAttributes = new HashMap<String, Object>(); populateMapFromJSONObject(previousAttributes, element.getAsJsonObject()); eventData.setPreviousAttributes(previousAttributes); } else if ("object".equals(key)) { String type = element.getAsJsonObject().get("object").getAsString(); Class<StripeObject> cl = objectMap.get(type); StripeObject object = APIResource.gson.fromJson(entry.getValue(), cl != null ? cl : StripeRawJsonObject.class); eventData.setObject(object); } } return eventData; } }
package com.tkhoon.framework.util; import java.io.FileWriter; import java.io.StringWriter; import java.util.Map; import org.apache.log4j.Logger; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.log.NullLogChute; public class VelocityUtil { private static final Logger logger = Logger.getLogger(VelocityUtil.class); private static final VelocityEngine engine = new VelocityEngine(); static { engine.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, ClassUtil.getClassPath()); engine.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8"); engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName()); } // VM classpath public static void setVmLoaderPath(String path) { engine.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); } public static void mergeTemplateIntoFile(String vmPath, Map<String, Object> dataMap, String filePath) { try { FileUtil.createFile(filePath); Template template = engine.getTemplate(vmPath); VelocityContext context = new VelocityContext(dataMap); FileWriter writer = new FileWriter(filePath); template.merge(context, writer); writer.close(); } catch (Exception e) { logger.error("", e); throw new RuntimeException(e); } } public static String mergeTemplateReturnString(String vmPath, Map<String, Object> dataMap) { String result; try { Template template = engine.getTemplate(vmPath); VelocityContext context = new VelocityContext(dataMap); StringWriter writer = new StringWriter(); template.merge(context, writer); result = writer.toString(); writer.close(); } catch (Exception e) { logger.error("", e); throw new RuntimeException(e); } return result; } }
package com.toedter.ms60min; import com.toedter.ms60min.thing.Thing; import com.toedter.ms60min.thing.ThingRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class Ms60minApplication { public static void main(String[] args) { // when deployed as a docker container to Heroku // Heroku sets the PORT environment variable // The DYNO environment variable is just to make sure to run in an Heroku environment String ENV_PORT = System.getenv().get("PORT"); String ENV_DYNO = System.getenv().get("DYNO"); if(ENV_PORT != null && ENV_DYNO != null) { System.getProperties().put("server.port", ENV_PORT); } SpringApplication.run(Ms60minApplication.class, args); } @Bean CommandLineRunner init(ThingRepository thingRepository) { return args -> { thingRepository.save(new Thing("1", "Hammer", "Orange")); thingRepository.save(new Thing("2", "Bike", "Red")); thingRepository.save(new Thing("3", "Car", "Blue")); }; } }
package com.treasure_data.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; 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.util.Calendar; import java.util.List; import java.util.Map; import org.msgpack.type.ArrayValue; import org.msgpack.type.BooleanValue; import org.msgpack.type.FloatValue; import org.msgpack.type.IntegerValue; import org.msgpack.type.MapValue; import org.msgpack.type.NilValue; import org.msgpack.type.NumberValue; import org.msgpack.type.RawValue; import org.msgpack.type.Value; /** * Data independed base class which implements the common part of all * resultsets. */ public abstract class TDResultSetBase implements ResultSet { private static final String INTVALUE_CLASSNAME = "org.msgpack.type.IntValueImpl"; private static final String LONGVALUE_CLASSNAME = "org.msgpack.type.LongValueImpl"; private static final String DOUBLEVALUE_CLASSNAME = "org.msgpack.type.DoubleValueImpl"; private static final String FLOATVALUE_CLASSNAME = "org.msgpack.type.FloatValueImpl"; protected SQLWarning warningChain = null; protected boolean wasNull = false; protected List<Object> row; protected List<String> columnNames; protected List<String> columnTypes; protected TDStatementBase statement = null; public boolean absolute(int row) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#absolute(int)")); } public void afterLast() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#afterLast()")); } public void beforeFirst() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#beforeFirst()")); } public void cancelRowUpdates() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#cancelRowUpdates()")); } public void deleteRow() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#deleteRow()")); } public int findColumn(String columnName) throws SQLException { int columnIndex = columnNames.indexOf(columnName); if (columnIndex == -1) { throw new SQLException("columnIndex: -1"); } else { return ++columnIndex; } } public boolean first() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#first()")); } public InputStream getAsciiStream(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getAsciiStream(int)")); } public InputStream getAsciiStream(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getAsciiStream(String)")); } public InputStream getBinaryStream(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBinaryStream(int)")); } public InputStream getBinaryStream(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBinaryStream(String)")); } public Reader getCharacterStream(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getCharacterStream(String)")); } public Reader getCharacterStream(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getCharacterStream(String)")); } public Reader getNCharacterStream(int index) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNCharacterStream(int)")); } public Reader getNCharacterStream(String name) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNCharacterStream(String)")); } public Array getArray(int i) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getArray(int)")); } public Array getArray(String colName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getArray(String)")); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBigDecimal(int)")); } public BigDecimal getBigDecimal(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBigDecimal(String)")); } public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBigDecimal(int, int)")); } public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBigDecimal(String, int)")); } public Blob getBlob(int i) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBlob(int)")); } public Blob getBlob(String colName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBlob(String)")); } public boolean getBoolean(int index) throws SQLException { return this.getBooleanWithTypeConversion(index); } public boolean getBoolean(String name) throws SQLException { return getBoolean(findColumn(name)); } private boolean getBooleanWithTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return false; } if (obj instanceof BooleanValue) { // msgpack's Boolean type return ((BooleanValue) obj).getBoolean(); } else if (obj instanceof Boolean) { // java's Boolean type return ((Boolean) obj).booleanValue(); } else if (obj instanceof NumberValue) { // msgpack's Number type return ((NumberValue) obj).asIntegerValue().intValue() != 0; } else if (obj instanceof Number) { // java's Number type return ((Number) obj).intValue() != 0; } else if (obj instanceof RawValue) { // msgpack's raw type return parseStringToBoolean(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return parseStringToBoolean((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to boolean", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } private static boolean parseStringToBoolean(String from) { if (from.toLowerCase().equals("false")) { return false; } else { return true; } } public byte getByte(int index) throws SQLException { return getByteWithImplicitTypeConversion(index); } public byte getByte(String name) throws SQLException { return getByte(findColumn(name)); } private byte getByteWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return (byte) ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (byte) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (byte) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (byte) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).byteValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Byte.parseByte(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Byte.parseByte((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to byte", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public byte[] getBytes(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBytes(int)")); } public byte[] getBytes(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getBytes(String)")); } public Clob getClob(int i) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getClob(int)")); } public Clob getClob(String colName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getClob(String)")); } public NClob getNClob(int index) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNClob(int)")); } public NClob getNClob(String columnLabel) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNClob(String)")); } public String getNString(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNString(int)")); } public String getNString(String columnLabel) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getNString(String)")); } public int getConcurrency() throws SQLException { return ResultSet.CONCUR_READ_ONLY; } public String getCursorName() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getCursorName()")); } public Date getDate(int index) throws SQLException { // TODO should implement more carefully // TODO Object obj = getObject(index); if (obj == null) { return null; } try { Value v = (Value) obj; return Date.valueOf(v.asRawValue().getString()); } catch (Exception e) { String msg = String.format( "Cannot convert column %d to date: %s", index, e.toString()); throw new SQLException(msg); } } public Date getDate(String columnName) throws SQLException { return getDate(findColumn(columnName)); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getDate(int, Calendar)")); } public Date getDate(String columnName, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getDate(String, Calendar)")); } public double getDouble(int index) throws SQLException { return getDoubleWithImplicitTypeConversion(index); } public double getDouble(String name) throws SQLException { return getDouble(findColumn(name)); } private double getDoubleWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0.0; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return (double) ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (double) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (double) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (double) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).doubleValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Double.parseDouble(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Double.parseDouble((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to double", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public int getFetchDirection() throws SQLException { return ResultSet.FETCH_FORWARD; } public int getFetchSize() throws SQLException { throw new SQLException("Method not supported"); } public float getFloat(int index) throws SQLException { return getFloatWithImplicitTypeConversion(index); } public float getFloat(String name) throws SQLException { return getFloat(findColumn(name)); } private float getFloatWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0.0f; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return (float) ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (float) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (float) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (float) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).floatValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Float.parseFloat(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Float.parseFloat((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to float", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public int getHoldability() throws SQLException { throw new SQLException("Method not supported"); } public int getInt(int index) throws SQLException { return getIntWithImplicitTypeConversion(index); } public int getInt(String name) throws SQLException { return getInt(findColumn(name)); } private int getIntWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (int) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (int) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (int) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).intValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Integer.parseInt(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Integer.parseInt((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to integer", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public long getLong(int index) throws SQLException { return getLongWithImplicitTypeConversion(index); } public long getLong(String name) throws SQLException { return getLong(findColumn(name)); } private long getLongWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return (long) ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (long) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (long) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (long) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).longValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Long.parseLong(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Long.parseLong((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to long", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public ResultSetMetaData getMetaData() throws SQLException { return new TDResultSetMetaData(columnNames, columnTypes); } public Object getObject(int columnIndex) throws SQLException { if (row == null) { throw new SQLException("No row found. If you don't call ResultSet#next method, please call it before calling getObject method to fetch rows."); } if (columnIndex > row.size()) { throw new SQLException("Invalid columnIndex: " + columnIndex); } try { wasNull = false; if (row.get(columnIndex - 1) == null) { wasNull = true; } return row.get(columnIndex - 1); } catch (Exception e) { throw new SQLException(e.toString()); } } public Object getObject(String columnName) throws SQLException { return getObject(findColumn(columnName)); } public Object getObject(int i, Map<String, Class<?>> map) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getObject(int, Map)")); } public Object getObject(String colName, Map<String, Class<?>> map) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getObject(String, Map)")); } public Ref getRef(int i) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getRef(int)")); } public Ref getRef(String colName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getRef(String)")); } public int getRow() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getRow(int)")); } public RowId getRowId(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getRowId(int)")); } public RowId getRowId(String columnLabel) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getRowId(String)")); } public SQLXML getSQLXML(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getSQLXML(int)")); } public SQLXML getSQLXML(String columnLabel) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getSQLXML(String)")); } public short getShort(int index) throws SQLException { return getShortWithImplicitTypeConversion(index); } public short getShort(String name) throws SQLException { return getShort(findColumn(name)); } private short getShortWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return 0; } if (obj instanceof NumberValue) { // msgpack's Number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return (short) ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return (short) ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return (short) ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return (short) ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's Number type return ((Number) obj).shortValue(); } else if (obj instanceof RawValue) { // msgpack's raw type return Short.parseShort(((RawValue) obj).getString()); } else if (obj instanceof String) { // java's raw type return Short.parseShort((String) obj); } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to byte", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } void setStatement(TDStatementBase stat) { statement = stat; } public Statement getStatement() throws SQLException { return statement; } /** * @param index * - the first column is 1, the second is 2, ... * @see java.sql.ResultSet#getString(int) */ public String getString(int index) throws SQLException { return getStringWithImplicitTypeConversion(index); } public String getString(String name) throws SQLException { return getString(findColumn(name)); } public String getStringWithImplicitTypeConversion(int index) throws SQLException { Throwable e = null; Object obj = null; try { obj = getObject(index); if (obj == null) { return null; } if (obj instanceof MapValue) { // msgpack's map type return ((MapValue) obj).toString(); } else if (obj instanceof ArrayValue) { // msgpack's array type return ((ArrayValue) obj).toString(); } else if (obj instanceof NumberValue) { // msgpack's number type NumberValue v = (NumberValue) obj; if (v instanceof IntegerValue) { if (v.getClass().getName().equals(INTVALUE_CLASSNAME)) { return "" + ((IntegerValue) v).getInt(); } else if (v.getClass().getName().equals(LONGVALUE_CLASSNAME)) { return "" + ((IntegerValue) v).getLong(); } } else { if (v.getClass().getName().equals(DOUBLEVALUE_CLASSNAME)) { return "" + ((FloatValue) v).doubleValue(); } else if (v.getClass().getName().equals(FLOATVALUE_CLASSNAME)) { return "" + ((FloatValue) v).floatValue(); } } } else if (obj instanceof Number) { // java's number type Number v = (Number) obj; if (v instanceof Byte) { return "" + ((Byte) v).byteValue(); } else if (v instanceof Double) { return "" + ((Double) v).doubleValue(); } else if (v instanceof Float) { return "" + ((Float) v).floatValue(); } else if (v instanceof Integer) { return "" + ((Integer) v).intValue(); } else if (v instanceof Short) { return "" + ((Short) v).shortValue(); } } else if (obj instanceof RawValue) { // msgpack's raw type return ((Value) obj).asRawValue().getString(); } else if (obj instanceof NilValue) { // msgpack's nil type return null; } else { // java's raw type return (String) obj; } } catch (Throwable t) { e = t; } // implicit type conversion failed String msg = String.format( "Cannot convert column %d from value of %s class to string", index, obj); if (e != null) { throw new SQLException(msg, e); } else { throw new SQLException(msg); } } public Time getTime(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTime(int)")); } public Time getTime(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTime(String)")); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTime(int, Calendar)")); } public Time getTime(String columnName, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTime(String, Calendar)")); } public Timestamp getTimestamp(int index) throws SQLException { Object obj = getObject(index); if (obj == null) { return null; } try { String type = columnTypes.get(index - 1); if (type.equalsIgnoreCase("timestamp")) { Value v = (Value) obj; return Timestamp.valueOf(v.asRawValue().getString()); } else { throw new IllegalArgumentException( "Expected column to be a timestamp type but is " + type); } } catch (Exception e) { String msg = String.format( "Cannot convert column %d to date: %s", index, e.toString()); throw new SQLException(msg); } } public Timestamp getTimestamp(String name) throws SQLException { return getTimestamp(findColumn(name)); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTimestamp(int, Calendar)")); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getTimestamp(String, Calendar)")); } public int getType() throws SQLException { return ResultSet.TYPE_FORWARD_ONLY; } public URL getURL(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getURL(int)")); } public URL getURL(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getURL(String)")); } public InputStream getUnicodeStream(int columnIndex) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getUnicodeStream(int)")); } public InputStream getUnicodeStream(String columnName) throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#getUnicodeStream(String)")); } public void insertRow() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#insertRow()")); } public boolean isAfterLast() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#isAfterLast()")); } public boolean isLast() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#isLast()")); } public boolean last() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#last()")); } public boolean isBeforeFirst() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#isBeforeFirst()")); } public boolean isFirst() throws SQLException { throw new SQLException(new UnsupportedOperationException( "TDResultSetBase#isFirst()")); } public boolean isClosed() throws SQLException { return false; } public void moveToCurrentRow() throws SQLException { throw new SQLException("Method not supported"); } public void moveToInsertRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean previous() throws SQLException { throw new SQLException("Method not supported"); } public void refreshRow() throws SQLException { throw new SQLException("Method not supported"); } public boolean relative(int rows) throws SQLException { throw new SQLException("Method not supported"); } public boolean rowDeleted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowInserted() throws SQLException { throw new SQLException("Method not supported"); } public boolean rowUpdated() throws SQLException { throw new SQLException("Method not supported"); } public void setFetchDirection(int direction) throws SQLException { throw new SQLException("Method not supported"); } public void setFetchSize(int rows) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(int columnIndex, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateArray(String columnName, Array x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnName, Blob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(int columnIndex, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateByte(String columnName, byte x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(int columnIndex, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateBytes(String columnName, byte[] x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnName, Clob x) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(int columnIndex, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDate(String columnName, Date x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(int columnIndex, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateDouble(String columnName, double x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(int columnIndex, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateFloat(String columnName, float x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(int columnIndex, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateInt(String columnName, int x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(int columnIndex, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateLong(String columnName, long x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, NClob clob) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(int columnIndex, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNString(String columnLabel, String string) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(int columnIndex) throws SQLException { throw new SQLException("Method not supported"); } public void updateNull(String columnName) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(int columnIndex, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(int columnIndex, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRef(String columnName, Ref x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRow() throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(int columnIndex, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateRowId(String columnLabel, RowId x) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(int columnIndex, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateShort(String columnName, short x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(int columnIndex, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateString(String columnName, String x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(int columnIndex, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTime(String columnName, Time x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public void updateTimestamp(String columnName, Timestamp x) throws SQLException { throw new SQLException("Method not supported"); } public SQLWarning getWarnings() throws SQLException { return warningChain; } public void clearWarnings() throws SQLException { warningChain = null; } public void close() throws SQLException { throw new SQLException("TDResultSetBase#close()"); } public boolean wasNull() throws SQLException { return wasNull; } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new SQLException("Method not supported"); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("Method not supported"); } }
package com.vmware.connection.helpers; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.vmware.connection.Connection; import com.vmware.connection.helpers.builders.*; import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.InvalidPropertyFaultMsg; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.ObjectSpec; import com.vmware.vim25.PropertyFilterSpec; import com.vmware.vim25.PropertySpec; import com.vmware.vim25.RetrieveOptions; import com.vmware.vim25.RetrieveResult; import com.vmware.vim25.RuntimeFaultFaultMsg; import com.vmware.vim25.SelectionSpec; import com.vmware.vim25.ServiceContent; import com.vmware.vim25.TraversalSpec; import com.vmware.vim25.VimPortType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class GetMOREF extends BaseHelper { private static final Logger LOG = LoggerFactory.getLogger(GetMOREF.class); private VimPortType vimPort; private ServiceContent serviceContent; public GetMOREF(final Connection connection) { super(connection); } /** * Initialize the helper object on the current connection at invocation time. Do not initialize on construction * since the connection may not be ready yet. */ private void init() { try { if (vimPort == null) vimPort = connection.connect().getVimPort(); if (serviceContent == null) serviceContent = connection.connect().getServiceContent(); } catch (Throwable cause) { LOG.error("Encountered error initializing MOREF", cause); Throwables.propagate(cause); } } public RetrieveResult containerViewByType( final ManagedObjectReference container, final String morefType, final RetrieveOptions retrieveOptions ) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { return this.containerViewByType(container,morefType,retrieveOptions,"name"); } /** * Returns the raw RetrieveResult object for the provided container filtered on properties list * * @param container - container to look in * @param morefType - type to filter for * @param morefProperties - properties to include * @return com.vmware.vim25.RetrieveResult for this query * @throws com.vmware.vim25.RuntimeFaultFaultMsg * @throws com.vmware.vim25.InvalidPropertyFaultMsg */ public RetrieveResult containerViewByType( final ManagedObjectReference container, final String morefType, final RetrieveOptions retrieveOptions, final String... morefProperties ) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { init(); PropertyFilterSpec[] propertyFilterSpecs = propertyFilterSpecs(container, morefType, morefProperties); return containerViewByType(container,morefType,morefProperties,retrieveOptions,propertyFilterSpecs); } public PropertyFilterSpec[] propertyFilterSpecs( ManagedObjectReference container, String morefType, String... morefProperties ) throws RuntimeFaultFaultMsg { init(); ManagedObjectReference viewManager = serviceContent.getViewManager(); ManagedObjectReference containerView = vimPort.createContainerView(viewManager, container, Arrays.asList(morefType), true); return new PropertyFilterSpec[]{ new PropertyFilterSpecBuilder() .propSet( new PropertySpecBuilder() .all(Boolean.FALSE) .type(morefType) .pathSet(morefProperties) ) .objectSet( new ObjectSpecBuilder() .obj(containerView) .skip(Boolean.TRUE) .selectSet( new TraversalSpecBuilder() .name("view") .path("view") .skip(false) .type("ContainerView") ) ) }; } public RetrieveResult containerViewByType( final ManagedObjectReference container, final String morefType, final String[] morefProperties, final RetrieveOptions retrieveOptions, final PropertyFilterSpec... propertyFilterSpecs ) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { init(); return vimPort.retrievePropertiesEx( serviceContent.getPropertyCollector(), Arrays.asList(propertyFilterSpecs), retrieveOptions ); } /** * Returns all the MOREFs of the specified type that are present under the * folder * * @param folder {@link com.vmware.vim25.ManagedObjectReference} of the folder to begin the search * from * @param morefType Type of the managed entity that needs to be searched * @return Map of name and MOREF of the managed objects present. If none * exist then empty Map is returned * @throws com.vmware.vim25.InvalidPropertyFaultMsg * * @throws com.vmware.vim25.RuntimeFaultFaultMsg * */ public Map<String, ManagedObjectReference> inFolderByType( final ManagedObjectReference folder, final String morefType, final RetrieveOptions retrieveOptions ) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { final PropertyFilterSpec[] propertyFilterSpecs = propertyFilterSpecs(folder, morefType, "name"); // reuse this property collector again later to scroll through results final ManagedObjectReference propertyCollector = serviceContent.getPropertyCollector(); RetrieveResult results = vimPort.retrievePropertiesEx( propertyCollector, Arrays.asList(propertyFilterSpecs), retrieveOptions); final Map<String, ManagedObjectReference> tgtMoref = Maps.newHashMap(); while(results != null && !results.getObjects().isEmpty()) { resultsToTgtMorefMap(results, tgtMoref); final String token = results.getToken(); // if we have a token, we can scroll through additional results, else there's nothing to do. results = (token != null) ? vimPort.continueRetrievePropertiesEx(propertyCollector,token) : null; } return tgtMoref; } private void resultsToTgtMorefMap(RetrieveResult results, Map<String, ManagedObjectReference> tgtMoref) { List<ObjectContent> oCont = (results != null) ? results.getObjects() : null; if (oCont != null) { for (ObjectContent oc : oCont) { ManagedObjectReference mr = oc.getObj(); String entityNm = null; List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { entityNm = (String) dp.getVal(); } } tgtMoref.put(entityNm, mr); } } } /** * Returns all the MOREFs of the specified type that are present under the * container * * @param container {@link com.vmware.vim25.ManagedObjectReference} of the container to begin the * search from * @param morefType Type of the managed entity that needs to be searched * @param morefProperties Array of properties to be fetched for the moref * @return Map of MOREF and Map of name value pair of properties requested of * the managed objects present. If none exist then empty Map is * returned * @throws com.vmware.vim25.InvalidPropertyFaultMsg * @throws com.vmware.vim25.RuntimeFaultFaultMsg */ public Map<ManagedObjectReference, Map<String, Object>> inContainerByType( ManagedObjectReference container, String morefType, String[] morefProperties, RetrieveOptions retrieveOptions) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { List<ObjectContent> oCont = containerViewByType(container, morefType, retrieveOptions, morefProperties).getObjects(); Map<ManagedObjectReference, Map<String, Object>> tgtMoref = Maps.newHashMap(); if (oCont != null) { for (ObjectContent oc : oCont) { Map<String, Object> propMap = Maps.newHashMap(); List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { propMap.put(dp.getName(), dp.getVal()); } } tgtMoref.put(oc.getObj(), propMap); } } return tgtMoref; } /** * Returns all the MOREFs of the specified type that are present under the * container * * @param folder {@link com.vmware.vim25.ManagedObjectReference} of the container to begin the * search from * @param morefType Type of the managed entity that needs to be searched * @return Map of name and MOREF of the managed objects present. If none * exist then empty Map is returned * @throws com.vmware.vim25.InvalidPropertyFaultMsg * @throws com.vmware.vim25.RuntimeFaultFaultMsg */ public Map<String, ManagedObjectReference> inContainerByType( ManagedObjectReference folder, String morefType, RetrieveOptions retrieveOptions) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { init(); RetrieveResult rslts = containerViewByType(folder, morefType, retrieveOptions); return toMap(rslts); } public Map<String, ManagedObjectReference> toMap(RetrieveResult rslts) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { final Map<String, ManagedObjectReference> tgtMoref = Maps.newHashMap(); String token = populate(rslts, tgtMoref); while (!Strings.isNullOrEmpty(token)) { // fetch results based on new token rslts = vimPort.continueRetrievePropertiesEx(serviceContent.getPropertyCollector(), token); token = populate(rslts, tgtMoref); } return tgtMoref; } public static String populate(final RetrieveResult rslts, final Map<String, ManagedObjectReference> tgtMoref) { String token = null; if (rslts != null) { token = rslts.getToken(); for(ObjectContent oc : rslts.getObjects()) { ManagedObjectReference mr = oc.getObj(); String entityNm = null; List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { entityNm = (String) dp.getVal(); } } tgtMoref.put(entityNm, mr); } } return token; } public static String populate(final RetrieveResult rslts, final List<ObjectContent> listobjcontent) { String token = null; if (rslts != null) { token = rslts.getToken(); listobjcontent.addAll(rslts.getObjects()); } return token; } /** * Get the MOR of the Virtual Machine by its name. * * @param vmName The name of the Virtual Machine * @param propCollectorRef * @return The Managed Object reference for this VM * @throws com.vmware.vim25.RuntimeFaultFaultMsg * @throws com.vmware.vim25.InvalidPropertyFaultMsg */ public ManagedObjectReference vmByVMname( final String vmName, final ManagedObjectReference propCollectorRef ) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { init(); ManagedObjectReference retVal = null; ManagedObjectReference rootFolder = serviceContent.getRootFolder(); TraversalSpec tSpec = getVMTraversalSpec(); // Create Property Spec PropertySpec propertySpec = new PropertySpecBuilder() .all(Boolean.FALSE) .pathSet("name") .type("VirtualMachine"); // Now create Object Spec ObjectSpec objectSpec = new ObjectSpecBuilder() .obj(rootFolder) .skip(Boolean.TRUE) .selectSet(tSpec); // Create PropertyFilterSpec using the PropertySpec and ObjectPec // created above. PropertyFilterSpec propertyFilterSpec = new PropertyFilterSpecBuilder() .propSet(propertySpec) .objectSet(objectSpec); List<PropertyFilterSpec> listpfs = Lists.newArrayList(); listpfs.add(propertyFilterSpec); RetrieveOptions options = new RetrieveOptions(); List<ObjectContent> listobcont = vimPort.retrievePropertiesEx(propCollectorRef, listpfs, options).getObjects(); if (listobcont != null) { for (ObjectContent oc : listobcont) { ManagedObjectReference mr = oc.getObj(); String vmnm = null; List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) { for (DynamicProperty dp : dps) { vmnm = (String) dp.getVal(); } } if (vmnm != null && vmnm.equals(vmName)) { retVal = mr; break; } } } return retVal; } /** * @return TraversalSpec specification to get to the VirtualMachine managed * object. */ public TraversalSpec getVMTraversalSpec() { // Create a traversal spec that starts from the 'root' objects // and traverses the inventory tree to get to the VirtualMachines. // Build the traversal specs bottoms up //Traversal to get to the VM in a VApp TraversalSpec vAppToVM = new TraversalSpecBuilder() .name("vAppToVM") .type("VirtualApp") .path("vm"); //Traversal spec for VApp to VApp TraversalSpec vAppToVApp = new TraversalSpecBuilder() .name("vAppToVApp") .type("VirtualApp") .path("resourcePool") .selectSet( //SelectionSpec for both VApp to VApp and VApp to VM new SelectionSpecBuilder().name("vAppToVApp"), new SelectionSpecBuilder().name("vAppToVM") ); //This SelectionSpec is used for recursion for Folder recursion SelectionSpec visitFolders = new SelectionSpecBuilder().name("VisitFolders"); // Traversal to get to the vmFolder from DataCenter TraversalSpec dataCenterToVMFolder = new TraversalSpecBuilder() .name("DataCenterToVMFolder") .type("Datacenter") .path("vmFolder") .skip(false) .selectSet(visitFolders); // TraversalSpec to get to the DataCenter from rootFolder return new TraversalSpecBuilder() .name("VisitFolders") .type("Folder") .path("childEntity") .skip(false) .selectSet( visitFolders, dataCenterToVMFolder, vAppToVM, vAppToVApp ); } /** * Method to retrieve properties of a {@link com.vmware.vim25.ManagedObjectReference} * * @param entityMor {@link com.vmware.vim25.ManagedObjectReference} of the entity * @param props Array of properties to be looked up * @return Map of the property name and its corresponding value * @throws com.vmware.vim25.InvalidPropertyFaultMsg If a property does not exist * @throws com.vmware.vim25.RuntimeFaultFaultMsg */ public Map<String, Object> entityProps( ManagedObjectReference entityMor, String[] props) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { init(); final HashMap<String, Object> retVal = Maps.newHashMap(); // Create PropertyFilterSpec using the PropertySpec and ObjectPec PropertyFilterSpec[] propertyFilterSpecs = { new PropertyFilterSpecBuilder() .propSet( // Create Property Spec new PropertySpecBuilder() .all(Boolean.FALSE) .type(entityMor.getType()) .pathSet(props) ) .objectSet( // Now create Object Spec new ObjectSpecBuilder() .obj(entityMor) ) }; List<ObjectContent> oCont = vimPort.retrievePropertiesEx(serviceContent.getPropertyCollector(), Arrays.asList(propertyFilterSpecs), new RetrieveOptions()).getObjects(); if (oCont != null) { for (ObjectContent oc : oCont) { List<DynamicProperty> dps = oc.getPropSet(); for (DynamicProperty dp : dps) { retVal.put(dp.getName(), dp.getVal()); } } } return retVal; } /** * Method to retrieve properties of list of {@link com.vmware.vim25.ManagedObjectReference} * * @param entityMors List of {@link com.vmware.vim25.ManagedObjectReference} for which the properties * needs to be retrieved * @param props Common properties that need to be retrieved for all the * {@link com.vmware.vim25.ManagedObjectReference} passed * @return Map of {@link com.vmware.vim25.ManagedObjectReference} and their corresponding name * value pair of properties * @throws com.vmware.vim25.InvalidPropertyFaultMsg * @throws com.vmware.vim25.RuntimeFaultFaultMsg */ public Map<ManagedObjectReference, Map<String, Object>> entityProps( List<ManagedObjectReference> entityMors, String[] props) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { init(); Map<ManagedObjectReference, Map<String, Object>> retVal = Maps.newHashMap(); // Create PropertyFilterSpec PropertyFilterSpecBuilder propertyFilterSpec = new PropertyFilterSpecBuilder(); Map<String, String> typesCovered = Maps.newHashMap(); for (ManagedObjectReference mor : entityMors) { if (!typesCovered.containsKey(mor.getType())) { // Create & add new property Spec propertyFilterSpec.propSet( new PropertySpecBuilder() .all(Boolean.FALSE) .type(mor.getType()) .pathSet(props) ); typesCovered.put(mor.getType(), ""); } // Now create & add Object Spec propertyFilterSpec.objectSet( new ObjectSpecBuilder().obj(mor) ); } List<PropertyFilterSpec> propertyFilterSpecs = ImmutableList.<PropertyFilterSpec>of(propertyFilterSpec); RetrieveResult rslts = vimPort.retrievePropertiesEx(serviceContent.getPropertyCollector(), propertyFilterSpecs, new RetrieveOptions()); List<ObjectContent> listobjcontent = Lists.newArrayList(); String token = populate(rslts,listobjcontent); while (token != null && !token.isEmpty()) { rslts = vimPort.continueRetrievePropertiesEx( serviceContent.getPropertyCollector(), token); token = populate(rslts,listobjcontent); } for (ObjectContent oc : listobjcontent) { List<DynamicProperty> dps = oc.getPropSet(); Map<String, Object> propMap = Maps.newHashMap(); if (dps != null) { for (DynamicProperty dp : dps) { propMap.put(dp.getName(), dp.getVal()); } } retVal.put(oc.getObj(), propMap); } return retVal; } public Map<String, ManagedObjectReference> inContainerByType(ManagedObjectReference container, String morefType) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { return inContainerByType(container, morefType, new RetrieveOptions()); } public Map<String,ManagedObjectReference> inFolderByType(ManagedObjectReference folder, String morefType) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg { return inFolderByType(folder,morefType, new RetrieveOptions()); } public Map<ManagedObjectReference,Map<String,Object>> inContainerByType(ManagedObjectReference container, String morefType, String[] strings) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg { return inContainerByType(container,morefType,strings,new RetrieveOptions()); } }
package de.domisum.lib.auxilium.util; import de.domisum.lib.auxilium.util.java.annotations.API; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBufferByte; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; @API @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ImageUtil { @API public static BufferedImage copy(RenderedImage bufferedImage) { ColorModel colorModel = bufferedImage.getColorModel(); boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied(); WritableRaster raster = bufferedImage.copyData(null); return new BufferedImage(colorModel, raster, isAlphaPremultiplied, null).getSubimage(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); } // TO PIXELS @API public static int[][] getPixels(BufferedImage image) { // TODO clean up this mess byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); int width = image.getWidth(); int height = image.getHeight(); boolean hasAlphaChannel = image.getAlphaRaster() != null; int[][] result = new int[height][width]; if(hasAlphaChannel) { int pixelLength = 4; int row = 0; int col = 0; for(int pixel = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; //argb += ((pixels[pixel]&0xff)<<24); // alpha argb += pixels[pixel+1]&0xff; // blue argb += (pixels[pixel+2]&0xff)<<8; // green argb += (pixels[pixel+3]&0xff)<<16; // red result[row][col] = argb; col++; if(col == width) { col = 0; row++; } } } else { int pixelLength = 3; int row = 0; int col = 0; for(int pixel = 0; pixel < pixels.length; pixel += pixelLength) { int argb = 0; //argb += -16777216; // 255 alpha argb += pixels[pixel]&0xff; // blue argb += (pixels[pixel+1]&0xff)<<8; // green argb += (pixels[pixel+2]&0xff)<<16; // red result[row][col] = argb; col++; if(col == width) { col = 0; row++; } } } return result; } // FROM PIXELS @API public static BufferedImage getImageFromPixels(int[] pixels, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster raster = (WritableRaster) bi.getData(); raster.setDataElements(0, 0, width, height, pixels); bi.setData(raster); return bi; } @API public static BufferedImage getImageFromPixels(int[][] pixels) { if((pixels.length == 0) || (pixels[0].length == 0)) throw new IllegalArgumentException("The array has to have at least a length of 1 in each direction"); int height = pixels.length; int width = pixels[0].length; int[] linearPixels = new int[width*height]; for(int i = 0; i < linearPixels.length; i++) { int column = i%width; int row = i/width; linearPixels[i] = pixels[row][column]; } return getImageFromPixels(linearPixels, width, height); } // COLOR @API public static BufferedImage dye(BufferedImage image, Color color) { BufferedImage graphicsImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = graphicsImage.createGraphics(); graphics2D.drawImage(image, 0, 0, null); graphics2D.setComposite(AlphaComposite.SrcAtop); graphics2D.setColor(color); graphics2D.fillRect(0, 0, image.getWidth(), image.getHeight()); return graphicsImage; } @API public static void saturize(BufferedImage image, double saturation) { for(int x = 0; x < image.getWidth(); x++) for(int y = 0; y < image.getHeight(); y++) image.setRGB(x, y, saturizePixel(image.getRGB(x, y), (float) saturation)); } private static int saturizePixel(int pixel, float saturation) { int red = 0xff&(pixel >> 16); int green = 0xff&(pixel >> 8); int blue = 0xff&pixel; float[] hsb = Color.RGBtoHSB(red, green, blue, null); hsb[1] += saturation; if(hsb[1] > 1) hsb[1] = 1; return Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]); } }