answer
stringlengths
17
10.2M
package org.metasyntactic.activities; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.*; import org.metasyntactic.NowPlayingControllerWrapper; import org.metasyntactic.data.Movie; import org.metasyntactic.data.Performance; import org.metasyntactic.data.Theater; import org.metasyntactic.utilities.MovieViewUtilities; import org.metasyntactic.utilities.StringUtilities; import java.util.ArrayList; import java.util.List; public class ShowtimesDetailsActivity extends ListActivity { private Theater theater; private Movie movie; private final List<TheaterDetailItem> detailItems = new ArrayList<TheaterDetailItem>(); private List<Performance> performances = new ArrayList<Performance>(); private final List<String> showtimes = new ArrayList<String>(); private final List<String> showtimes_url = new ArrayList<String>(); private enum TheaterDetailItemType { NAME_SHOWTIMES, ADDRESS, PHONE } @Override protected void onListItemClick(final ListView listView, final View view, final int position, final long id) { final Intent intent = detailItems.get(position).getIntent(); if (intent != null) { startActivity(intent); } super.onListItemClick(listView, view, position, id); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(getClass().getSimpleName(), "onCreate"); NowPlayingControllerWrapper.addActivity(this); setContentView(R.layout.showtimedetails); movie = getIntent().getExtras().getParcelable("movie"); theater = getIntent().getExtras().getParcelable("theater"); performances = NowPlayingControllerWrapper.getPerformancesForMovieAtTheater(movie, theater); for (final Performance per : performances) { if (per != null && !StringUtilities.isNullOrEmpty(per.getUrl())) { showtimes.add(per.getTime()); showtimes_url.add(per.getUrl()); } } populateTheaterDetailItem(); final TheaterAdapter theaterAdapter = new TheaterAdapter(); setListAdapter(theaterAdapter); final TextView theaterTxt = (TextView) findViewById(R.id.theater); theaterTxt.setText(theater.getName()); final Button orderTickets = (Button) findViewById(R.id.showtimes); orderTickets.setOnClickListener(new OnClickListener() { public void onClick(final View v) { showDialog(1); } }); if (!showtimes.isEmpty()) { findViewById(R.id.bottom_bar).setVisibility(View.VISIBLE); } } @Override protected void onResume() { super.onResume(); Log.i(getClass().getSimpleName(), "onResume"); } @Override protected void onPause() { super.onPause(); Log.i(getClass().getSimpleName(), "onPause"); } @Override protected void onDestroy() { Log.i(getClass().getSimpleName(), "onDestroy"); NowPlayingControllerWrapper.removeActivity(this); super.onDestroy(); } @Override public Object onRetainNonConfigurationInstance() { Log.i(getClass().getSimpleName(), "onRetainNonConfigurationInstance"); final Object result = new Object(); NowPlayingControllerWrapper.onRetainNonConfigurationInstance(this, result); return result; } private void populateTheaterDetailItem() { // Add name_showtimes type TheaterDetailItem entry1 = new TheaterDetailItem(); entry1.setType(TheaterDetailItemType.NAME_SHOWTIMES); detailItems.add(entry1); // Add address type entry1 = new TheaterDetailItem(); entry1.setType(TheaterDetailItemType.ADDRESS); detailItems.add(entry1); // Add phone type entry1 = new TheaterDetailItem(); entry1.setType(TheaterDetailItemType.PHONE); detailItems.add(entry1); } private class TheaterAdapter extends BaseAdapter { private final LayoutInflater inflater; private TheaterAdapter() { // Cache the LayoutInflate to avoid asking for a new one each time. inflater = LayoutInflater.from(ShowtimesDetailsActivity.this); } public View getView(final int position, View convertView, final ViewGroup viewGroup) { convertView = inflater.inflate(R.layout.showtimes_item, null); final Resources res = getResources(); final TheaterDetailsViewHolder holder = new TheaterDetailsViewHolder((TextView) convertView.findViewById(R.id.label), (ImageView) convertView .findViewById(R.id.icon), (TextView) convertView.findViewById(R.id.data)); final int theaterIndex = position / TheaterDetailItemType.values().length; switch (detailItems.get(position).getType()) { case NAME_SHOWTIMES: holder.label.setText(res.getString(R.string.showtimes_for, movie.getCanonicalTitle(), theater.getName())); holder.icon.setImageDrawable(getResources().getDrawable(R.drawable.sym_action_email)); String performance = ""; for (final Performance per : performances) { performance += per.getTime() + ", "; } performance = performance.substring(0, performance.length() - 2); holder.data.setText(performance); final String addr = "user@example.com"; final Intent intent1 = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + addr)); intent1.putExtra("subject", res.getString(R.string.showtimes_for, movie.getDisplayTitle(), theater.getName())); intent1.putExtra("body", performance); detailItems.get(position).setIntent(intent1); break; case PHONE: holder.data.setText(theater.getPhoneNumber()); holder.icon.setImageDrawable(getResources().getDrawable(R.drawable.sym_action_call)); holder.label.setText(res.getString(R.string.call)); final Intent intent2 = new Intent("android.intent.action.DIAL", Uri.parse("tel:" + theater.getPhoneNumber())); detailItems.get(position).setIntent(intent2); break; case ADDRESS: final String address = theater.getAddress() + ", " + theater.getLocation().getCity(); holder.data.setText(address); holder.icon.setImageDrawable(getResources().getDrawable(R.drawable.sym_action_map)); holder.label.setText(res.getString(R.string.location)); final Intent intent3 = new Intent("android.intent.action.VIEW", Uri.parse("geo:0,0?q=" + address)); detailItems.get(position).setIntent(intent3); } return convertView; } public int getCount() { return detailItems.size(); } private class TheaterDetailsViewHolder { private final TextView label; private final ImageView icon; private final TextView data; private TheaterDetailsViewHolder(final TextView label, final ImageView icon, final TextView data) { this.label = label; this.icon = icon; this.data = data; } } public long getEntryId(final int position) { return position; } public Object getItem(final int position) { return detailItems.get(position); } public long getItemId(final int position) { return position; } public void refresh() { notifyDataSetChanged(); } } private static class TheaterDetailItem { private TheaterDetailItemType type; private Intent intent; public Intent getIntent() { return intent; } public void setIntent(final Intent intent) { this.intent = intent; } public TheaterDetailItemType getType() { return type; } public void setType(final TheaterDetailItemType type) { this.type = type; } } @Override public boolean onCreateOptionsMenu(final Menu menu) { menu.add(0, MovieViewUtilities.MENU_MOVIES, 0, R.string.menu_movies).setIcon(R.drawable.ic_menu_home).setIntent( new Intent(this, NowPlayingActivity.class)); menu.add(0, MovieViewUtilities.MENU_SETTINGS, 0, R.string.settings).setIcon(android.R.drawable.ic_menu_preferences).setIntent( new Intent(this, SettingsActivity.class)); return super.onCreateOptionsMenu(menu); } @Override protected Dialog onCreateDialog(final int id) { final String[] criteria = new String[showtimes.size()]; showtimes.toArray(criteria); return new AlertDialog.Builder(this).setTitle(R.string.order_tickets).setItems(criteria, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { final String order_url = showtimes_url.get(which); final Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(order_url)); startActivity(intent); } }).create(); } }
package com.wikia.pandora.core.impl.configuration; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Nonnull; import javax.validation.Valid; import javax.validation.constraints.NotNull; import io.dropwizard.Configuration; import io.dropwizard.client.HttpClientConfiguration; public class PandoraConfiguration extends Configuration { @Valid @NotNull private String internalProxyHost; @Valid @NotNull private Integer internalProxyPort = 80; @Valid @NotNull @JsonProperty private final HttpClientConfiguration httpClient; public PandoraConfiguration() { httpClient = new HttpClientConfiguration(); } @JsonProperty public String getInternalProxyHost() { return internalProxyHost; } @JsonProperty public void setInternalProxyHost(String internalProxyHost) { this.internalProxyHost = internalProxyHost; } @JsonProperty public Integer getInternalProxyPort() { return internalProxyPort; } @JsonProperty public void setInternalProxyPort(Integer internalProxyPort) { this.internalProxyPort = internalProxyPort; } public HttpClientConfiguration getHttpClientConfiguration() { return httpClient; } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.jpa.datasource.PoolConfig; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.utils.ObjectUtils; import org.yaml.snakeyaml.Yaml; /** * Easy way to retrieve configuration properties from configuration file * * @author levan * */ public class Configuration implements Cloneable { // cache for all configuration passed programmatically or read from file private final Map<Object, Object> config = new HashMap<Object, Object>(); // path where stored adminitrator users public static final String ADMIN_USERS_PATH_KEY = "adminUsersPath"; /** * <a href="netty.io">Netty</a> server / client configuration properties for * RPC calls */ public static final String IP_ADDRESS_KEY = "listeningIp"; public static final String PORT_KEY = "listeningPort"; public static final String BOSS_POOL_KEY = "bossPoolSize"; public static final String WORKER_POOL_KEY = "workerPoolSize"; public static final String CONNECTION_TIMEOUT_KEY = "timeout"; // properties for datasource path and deployment path public static final String DEMPLOYMENT_PATH_KEY = "deploymentPath"; public static final String DATA_SOURCE_PATH_KEY = "dataSourcePath"; // runtime to get avaliable processors private static final Runtime RUNTIME = Runtime.getRuntime(); /** * Default properties */ public static final String ADMIN_USERS_PATH_DEF = "./config/admin/users.properties"; public static final String IP_ADDRESS_DEF = "0.0.0.0"; public static final String PORT_DEF = "1199"; public static final String BOSS_POOL_DEF = "1"; public static final int WORKER_POOL_DEF = 3; public static final String CONNECTION_TIMEOUT_DEF = "1000"; public static final boolean SERVER_DEF = Boolean.TRUE; public static final String DATA_SOURCE_PATH_DEF = "./ds"; /** * Properties which version of server is running remote it requires server * client RPC infrastructure or local (embeddable mode) */ private static final String REMOTE_KEY = "remote"; private static final String SERVER_KEY = "server"; private static final String CLIENT_KEY = "client"; public static final Set<DeploymentDirectory> DEPLOYMENT_PATHS_DEF = new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE))); public static final Set<String> DATA_SOURCES_PATHS_DEF = new HashSet<String>( Arrays.asList("./ds")); private static final String CONFIG_FILE = "./config/configuration.yaml"; // String prefixes for jndi names public static final String JPA_NAME = "java:comp/env/"; public static final String EJB_NAME = "ejb:"; public static final int EJB_NAME_LENGTH = 4; // Configuration keys properties for deployment private static final String DEPLOY_CONFIG_KEY = "deployConfiguration"; private static final String ADMIN_USER_PATH_KEY = "adminPath"; private static final String HOT_DEPLOYMENT_KEY = "hotDeployment"; private static final String WATCH_STATUS_KEY = "watchStatus"; private static final String LIBRARY_PATH_KEY = "libraryPaths"; // Persistence provider property keys private static final String PERSISTENCE_CONFIG_KEY = "persistenceConfig"; private static final String SCAN_FOR_ENTITIES_KEY = "scanForEntities"; private static final String ANNOTATED_UNIT_NAME_KEY = "annotatedUnitName"; private static final String PERSISTENCE_XML_PATH_KEY = "persistanceXmlPath"; private static final String PERSISTENCE_XML_FROM_JAR_KEY = "persistenceXmlFromJar"; private static final String SWAP_DATASOURCE_KEY = "swapDataSource"; private static final String SCAN_ARCHIVES_KEY = "scanArchives"; private static final String POOLED_DATA_SOURCE_KEY = "pooledDataSource"; private static final String PERSISTENCE_PROPERTIES_KEY = "persistenceProperties"; // Connection pool provider property keys private static final String POOL_CONFIG_KEY = "poolConfig"; private static final String POOL_PROPERTIES_PATH_KEY = "poolPropertiesPath"; private static final String POOL_PROVIDER_TYPE_KEY = "poolProviderType"; private static final String POOL_PROPERTIES_KEY = "poolProperties"; // Configuration properties for deployment private static String ADMIN_USERS_PATH; // Is configuration server or client (default is server) private static boolean server = SERVER_DEF; private static boolean remote; // Instance of pool configuration private static final PoolConfig POOL_CONFIG = new PoolConfig(); private static final Logger LOG = Logger.getLogger(Configuration.class); public Configuration() { } @SuppressWarnings("unchecked") private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } Map<K, V> value = (Map<K, V>) ObjectUtils.getAsMap(key, from); return value; } private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (ObjectUtils.available(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } private <K> boolean containsSubConfigKey(Object key, K subKey) { Map<K, ?> subConfig = getAsMap(key); boolean valid = ObjectUtils.available(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } private <K> boolean containsConfigKey(K key) { return containsSubConfigKey(DEPLOY_CONFIG_KEY, key); } private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } private <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(DEPLOY_CONFIG_KEY, subKey, value); } private <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey, defaultValue); } private <K, V> V getConfigValue(K subKey) { return getSubConfigValue(DEPLOY_CONFIG_KEY, subKey); } private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } private <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } public <V> V getPersistenceConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, PERSISTENCE_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } public <V> V getPersistenceConfigValue(Object key) { return getPersistenceConfigValue(key, null); } /** * Sets specific value for appropriated key in persistence configuration sub * {@link Map} of configuration * * @param key * @param value */ public void setPersistenceConfigValue(Object key, Object value) { setWithInitialization(PERSISTENCE_CONFIG_KEY, key, value); } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration if value is null then returns passed default * value * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key, V defaultValue) { V value = ObjectUtils.getSubValue(config, DEPLOY_CONFIG_KEY, POOL_CONFIG_KEY, key); if (value == null) { value = defaultValue; } return value; } /** * Gets value for specific key from connection pool configuration sub * {@link Map} of configuration * * @param key * @return <code>V</code> */ public <V> V getPoolConfigValue(Object key) { V value = getPoolConfigValue(key, null); return value; } /** * Sets specific value for appropriated key in connection pool configuration * sub {@link Map} of configuraion * * @param key * @param value */ public void setPoolConfigValue(Object key, Object value) { setWithInitialization(POOL_CONFIG_KEY, key, value); } /** * Configuration for {@link PoolConfig} instance */ private void configurePool() { Map<Object, Object> poolProperties = getPoolConfigValue(POOL_PROPERTIES_KEY); if (ObjectUtils.available(poolProperties)) { setPoolProperties(poolProperties); } String type = getPoolConfigValue(POOL_PROVIDER_TYPE_KEY); if (ObjectUtils.available(type)) { getPoolConfig().setPoolProviderType(type); } String path = getPoolConfigValue(POOL_PROPERTIES_PATH_KEY); if (ObjectUtils.available(path)) { setPoolPropertiesPath(path); } } /** * Configures server from properties */ private void configureServer() { // Sets default values to remote server configuration boolean contains = containsConfigKey(IP_ADDRESS_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(IP_ADDRESS_KEY, IP_ADDRESS_DEF); } contains = containsConfigKey(PORT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(PORT_KEY, PORT_DEF); } contains = containsConfigKey(BOSS_POOL_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(BOSS_POOL_KEY, BOSS_POOL_DEF); } contains = containsConfigKey(WORKER_POOL_KEY); if (ObjectUtils.notTrue(contains)) { int workers = RUNTIME.availableProcessors() * WORKER_POOL_DEF; String workerProperty = String.valueOf(workers); setConfigValue(WORKER_POOL_KEY, workerProperty); } contains = containsConfigKey(CONNECTION_TIMEOUT_KEY); if (ObjectUtils.notTrue(contains)) { setConfigValue(CONNECTION_TIMEOUT_KEY, CONNECTION_TIMEOUT_DEF); } // Sets default values is application on server or client mode Object serverValue = getConfigValue(SERVER_KEY); if (ObjectUtils.notNull(serverValue)) { if (serverValue instanceof Boolean) { server = (Boolean) serverValue; } else { server = Boolean.valueOf(serverValue.toString()); } } Object remoteValue = getConfigValue(REMOTE_KEY); if (ObjectUtils.notNull(remoteValue)) { if (remoteValue instanceof Boolean) { remote = (Boolean) remoteValue; } else { remote = Boolean.valueOf(remoteValue.toString()); } } } /** * Merges configuration with default properties */ public void configureDeployments() { // Sets administrator user configuration file path ADMIN_USERS_PATH = getConfigValue(ADMIN_USER_PATH_KEY, ADMIN_USERS_PATH_DEF); // Checks if application run in hot deployment mode Boolean hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); if (hotDeployment == null) { setConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); hotDeployment = getConfigValue(HOT_DEPLOYMENT_KEY); } // Check if application needs directory watch service boolean watchStatus; if (ObjectUtils.notTrue(hotDeployment)) { watchStatus = Boolean.TRUE; } else { watchStatus = Boolean.FALSE; } setConfigValue(WATCH_STATUS_KEY, watchStatus); // Sets deployments directories Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = DEPLOYMENT_PATHS_DEF; setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } } /** * Configures server and connection pooling */ public void configure() { configureServer(); configureDeployments(); configurePool(); } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return {@link Map}<Object, Object> */ @SuppressWarnings("unchecked") protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); Object key; Map<Object, Object> value1; Object value2; Object mergedValue; for (Map.Entry<Object, Object> entry2 : entries2) { key = entry2.getKey(); value2 = entry2.getValue(); if (value2 instanceof Map) { value1 = ObjectUtils.getAsMap(key, map1); mergedValue = deepMerge(value1, (Map<Object, Object>) value2); } else { mergedValue = value2; } if (ObjectUtils.notNull(mergedValue)) { map1.put(key, mergedValue); } } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Reads configuration from passed file path * * @param configuration */ @SuppressWarnings("unchecked") public void configure(String path) throws IOException { File yamlFile = new File(path); if (yamlFile.exists()) { InputStream stream = new FileInputStream(yamlFile); try { Yaml yaml = new Yaml(); Object configuration = yaml.load(stream); if (configuration instanceof Map) { configure((Map<Object, Object>) configuration); } } finally { stream.close(); } } } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { Object value = config.get(key); String textValue; if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { InputStream propertiesStream = null; try { File configFile = new File(CONFIG_FILE); if (configFile.exists()) { propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error("Could not open config file", ex); } finally { if (ObjectUtils.notNull(propertiesStream)) { propertiesStream.close(); } } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { InputStream propertiesStream = null; try { propertiesStream = new FileInputStream(new File(configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error("Could not open config file", ex); } finally { if (ObjectUtils.notNull(propertiesStream)) { propertiesStream.close(); } } } /** * Loads configuration from file contained in classpath * * @param resourceName * @param loader */ public void loadFromResource(String resourceName, ClassLoader loader) { InputStream resourceStream = loader .getResourceAsStream(new StringBuilder("META-INF/").append( resourceName).toString()); if (resourceStream == null) { LOG.error("Configuration resource doesn't exist"); return; } loadFromStream(resourceStream); try { resourceStream.close(); } catch (IOException ex) { LOG.error("Could not load resource", ex); } } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @throws IOException */ public void loadFromStream(InputStream propertiesStream) { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } propertiesStream.close(); } catch (IOException ex) { LOG.error("Could not load configuration", ex); } } public static String getAdminUsersPath() { return ADMIN_USERS_PATH; } public static void setAdminUsersPath(String aDMIN_USERS_PATH) { ADMIN_USERS_PATH = aDMIN_USERS_PATH; } public boolean isRemote() { return remote; } public void setRemote(boolean remoteValue) { remote = remoteValue; } public static boolean isServer() { return server; } public static void setServer(boolean serverValue) { server = serverValue; } public boolean isClient() { return getConfigValue(CLIENT_KEY, Boolean.FALSE); } public void setClient(boolean client) { setConfigValue(CLIENT_KEY, client); } /** * Adds path for deployments file or directory * * @param path * @param scan */ public void addDeploymentPath(String path, boolean scan) { Set<DeploymentDirectory> deploymentPaths = getConfigValue(DEMPLOYMENT_PATH_KEY); if (deploymentPaths == null) { deploymentPaths = new HashSet<DeploymentDirectory>(); setConfigValue(DEMPLOYMENT_PATH_KEY, deploymentPaths); } deploymentPaths.add(new DeploymentDirectory(path, scan)); } /** * Adds path for data source file * * @param path */ public void addDataSourcePath(String path) { Set<String> dataSourcePaths = getConfigValue(DATA_SOURCE_PATH_KEY); if (dataSourcePaths == null) { dataSourcePaths = new HashSet<String>(); setConfigValue(DATA_SOURCE_PATH_KEY, dataSourcePaths); } dataSourcePaths.add(path); } public Set<DeploymentDirectory> getDeploymentPath() { return getConfigValue(DEMPLOYMENT_PATH_KEY); } public Set<String> getDataSourcePath() { return getConfigValue(DATA_SOURCE_PATH_KEY); } public String[] getLibraryPaths() { return getConfigValue(LIBRARY_PATH_KEY); } public void setLibraryPaths(String[] libraryPaths) { setConfigValue(LIBRARY_PATH_KEY, libraryPaths); } public boolean isHotDeployment() { return getConfigValue(HOT_DEPLOYMENT_KEY, Boolean.FALSE); } public void setHotDeployment(boolean hotDeployment) { setConfigValue(HOT_DEPLOYMENT_KEY, hotDeployment); } public boolean isWatchStatus() { return getConfigValue(WATCH_STATUS_KEY, Boolean.FALSE); } public void setWatchStatus(boolean watchStatus) { setConfigValue(WATCH_STATUS_KEY, watchStatus); } // Persistence configuration public boolean isScanForEntities() { return getPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, Boolean.FALSE); } public void setScanForEntities(boolean scanForEntities) { setPersistenceConfigValue(SCAN_FOR_ENTITIES_KEY, scanForEntities); } public String getAnnotatedUnitName() { return getPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY); } public void setAnnotatedUnitName(String annotatedUnitName) { setPersistenceConfigValue(ANNOTATED_UNIT_NAME_KEY, annotatedUnitName); } public String getPersXmlPath() { return getPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY); } public void setPersXmlPath(String persXmlPath) { setPersistenceConfigValue(PERSISTENCE_XML_PATH_KEY, persXmlPath); } public boolean isPersXmlFromJar() { return getPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, Boolean.FALSE); } public void setPersXmlFromJar(boolean persXmlFromJar) { setPersistenceConfigValue(PERSISTENCE_XML_FROM_JAR_KEY, persXmlFromJar); } public boolean isSwapDataSource() { return getPersistenceConfigValue(SWAP_DATASOURCE_KEY, Boolean.FALSE); } public void setSwapDataSource(boolean swapDataSource) { setPersistenceConfigValue(SWAP_DATASOURCE_KEY, swapDataSource); } public boolean isScanArchives() { return getPersistenceConfigValue(SCAN_ARCHIVES_KEY, Boolean.FALSE); } public void setScanArchives(boolean scanArchives) { setPersistenceConfigValue(SCAN_ARCHIVES_KEY, scanArchives); } public boolean isPooledDataSource() { return getPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, Boolean.FALSE); } public void setPooledDataSource(boolean pooledDataSource) { setPersistenceConfigValue(POOLED_DATA_SOURCE_KEY, pooledDataSource); } public Map<Object, Object> getPersistenceProperties() { return getPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY); } public void setPersistenceProperties( Map<Object, Object> persistenceProperties) { setPersistenceConfigValue(PERSISTENCE_PROPERTIES_KEY, persistenceProperties); } // Pool configuration public static PoolConfig getPoolConfig() { return POOL_CONFIG; } public void setDataSourcePooledType(boolean dsPooledType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPooledDataSource(dsPooledType); } public void setPoolPropertiesPath(String path) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolPath(path); } public void setPoolProperties( Map<? extends Object, ? extends Object> properties) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().putAll(properties); } public void addPoolProperty(Object key, Object value) { PoolConfig poolConfig = getPoolConfig(); poolConfig.getPoolProperties().put(key, value); } public void setPoolProviderType(PoolProviderType poolProviderType) { PoolConfig poolConfig = getPoolConfig(); poolConfig.setPoolProviderType(poolProviderType); } @Override public Object clone() throws CloneNotSupportedException { Configuration cloneConfig = (Configuration) super.clone(); cloneConfig.config.clear(); cloneConfig.configure(this.config); return cloneConfig; } }
package org.pentaho.reporting.libraries.pensol; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.vfs.Capability; import org.apache.commons.vfs.FileName; import org.apache.commons.vfs.FileSystem; import org.apache.commons.vfs.FileSystemException; import org.apache.commons.vfs.FileSystemOptions; import org.apache.commons.vfs.UserAuthenticationData; import org.apache.commons.vfs.provider.AbstractOriginatingFileProvider; import org.apache.commons.vfs.provider.GenericFileName; import org.apache.commons.vfs.provider.LayeredFileName; import org.apache.commons.vfs.provider.LayeredFileNameParser; import org.apache.commons.vfs.provider.http.HttpClientFactory; import org.apache.commons.vfs.util.UserAuthenticatorUtils; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.engine.core.system.PentahoSessionHolder; import org.pentaho.reporting.libraries.pensol.vfs.LocalFileModel; import org.pentaho.reporting.libraries.pensol.vfs.WebSolutionFileSystem; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class PentahoSolutionFileProvider extends AbstractOriginatingFileProvider { private static final Log logger = LogFactory.getLog( PentahoSolutionFileProvider.class ); private boolean bypassAuthentication = false; public static final Collection capabilities = Collections.unmodifiableCollection( Arrays.asList ( Capability.GET_TYPE, Capability.GET_LAST_MODIFIED, Capability.LIST_CHILDREN, Capability.READ_CONTENT, Capability.CREATE, Capability.FS_ATTRIBUTES, Capability.URI ) ); public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD // future: Publish Password for write access .. }; public PentahoSolutionFileProvider() { setFileNameParser( LayeredFileNameParser.getInstance() ); // check if can bypass authentication try { IPentahoSession session = PentahoSessionHolder.getSession(); if ( session != null ) { // running locally => access directly bypassing authentication this.bypassAuthentication = true; } } catch ( NoClassDefFoundError e ) { // no server running } } /** * Creates a {@link org.apache.commons.vfs.FileSystem}. If the returned FileSystem implements {@link * org.apache.commons.vfs.provider.VfsComponent}, it will be initialised. * * @param rootName The name of the root file of the file system to create. */ protected FileSystem doCreateFileSystem( final FileName rootName, final FileSystemOptions fileSystemOptions ) throws FileSystemException { final LayeredFileName genericRootName = (LayeredFileName) rootName; if ( "jcr-solution".equals( rootName.getScheme() ) ) { // bypass authentication if running inside server if ( this.bypassAuthentication ) { return createJCRDirectFileSystem( genericRootName, fileSystemOptions ); } return createJCRFileSystem( genericRootName, fileSystemOptions ); } return createWebFileSystem( genericRootName, fileSystemOptions ); } private FileSystem createJCRDirectFileSystem( final LayeredFileName genericRootName, final FileSystemOptions fileSystemOptions ) throws FileSystemException { final JCRSolutionDirectFileModel model = new JCRSolutionDirectFileModel(); return new JCRSolutionDirectFileSystem( genericRootName, fileSystemOptions, model ); } private FileSystem createJCRFileSystem( final LayeredFileName genericRootName, final FileSystemOptions fileSystemOptions ) { UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate( fileSystemOptions, AUTHENTICATOR_TYPES ); final GenericFileName outerName = (GenericFileName) genericRootName.getOuterName(); final String username = UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData ( authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar( outerName.getUserName() ) ) ); final String password = UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData ( authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar( outerName.getPassword() ) ) ); final PentahoSolutionsFileSystemConfigBuilder configBuilder = new PentahoSolutionsFileSystemConfigBuilder(); final int timeOut = configBuilder.getTimeOut( fileSystemOptions ); final JCRSolutionFileModel model = new JCRSolutionFileModel( outerName.getURI(), username, password, timeOut ); return new JCRSolutionFileSystem( genericRootName, fileSystemOptions, model ); } finally { UserAuthenticatorUtils.cleanup( authData ); } } private FileSystem createWebFileSystem( final LayeredFileName genericRootName, final FileSystemOptions fileSystemOptions ) throws FileSystemException { UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate( fileSystemOptions, AUTHENTICATOR_TYPES ); final GenericFileName outerName = (GenericFileName) genericRootName.getOuterName(); final HttpClient httpClient = HttpClientFactory.createConnection( outerName.getScheme(), outerName.getHostName(), outerName.getPort(), UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData ( authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar( outerName.getUserName() ) ) ), UserAuthenticatorUtils.toString( UserAuthenticatorUtils.getData ( authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar( outerName.getPassword() ) ) ), fileSystemOptions ); httpClient.getParams().setAuthenticationPreemptive( true ); final PentahoSolutionsFileSystemConfigBuilder configBuilder = new PentahoSolutionsFileSystemConfigBuilder(); final int timeOut = configBuilder.getTimeOut( fileSystemOptions ); httpClient.getParams().setSoTimeout( Math.max( 0, timeOut ) ); return new WebSolutionFileSystem( genericRootName, fileSystemOptions, new LocalFileModel( outerName.getURI(), httpClient, outerName.getUserName(), outerName.getPassword() ) ); } finally { UserAuthenticatorUtils.cleanup( authData ); } } /** * Get the filesystem capabilities.<br> These are the same as on the filesystem, but available before the first * filesystem was instanciated. */ public Collection getCapabilities() { return capabilities; } }
package org.lightmare.rest.utils; import java.io.IOException; import java.util.Iterator; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ws.rs.Path; import org.glassfish.jersey.server.model.Resource; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.MetaData; import org.lightmare.cache.RestContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.RestConfig; import org.lightmare.rest.providers.RestReloader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.serialization.JsonSerializer; /** * Utility class for REST resources * * @author levan * */ public class RestUtils { private static RestConfig newConfig; private static final Lock lock = new ReentrantLock(); private static void getConfig() { if (newConfig == null) { newConfig = new RestConfig(Boolean.FALSE); } } private static RestConfig get() { if (newConfig == null) { lock.lock(); try { getConfig(); } finally { lock.unlock(); } } return newConfig; } public static <T> T convert(String json, Class<T> valueClass) throws IOException { T value = JsonSerializer.read(json, valueClass); return value; } public static String json(Object data) throws IOException { return JsonSerializer.write(data); } /** * Checks if class is acceptable to build {@link Resource} instance * * @param resourceClass * @return <code>boolean</code> */ private static boolean isAcceptable(Class<?> resourceClass) { boolean valid = Resource.isAcceptable(resourceClass) && resourceClass.isAnnotationPresent(Path.class); return valid; } /** * Adds bean {@link Class} as * {@link org.glassfish.jersey.server.model.Resource} to {@link RestConfig} * instance * * @param beanClass * @throws IOException */ public static void add(Class<?> beanClass) throws IOException { boolean valid = isAcceptable(beanClass); if (valid) { RestReloader reloader = RestReloader.get(); if (ObjectUtils.notNull(reloader)) { RestConfig conf = get(); RestConfig existingConfig = RestContainer.getRestConfig(); conf.registerClass(beanClass, existingConfig); } } } /** * Removes bean {@link Class} as * {@link org.glassfish.jersey.server.model.Resource} to {@link RestConfig} * instance * * @param beanClass */ public static void remove(Class<?> beanClass) { RestReloader reloader = RestReloader.get(); if (ObjectUtils.notNull(reloader)) { RestConfig conf = get(); conf.unregister(beanClass); } } /** * Gets common class loader (enriched for each {@link ClassLoader} from * {@link MetaData}) to add to REST server * * @return {@link ClassLoader} */ public static ClassLoader getCommonLoader() { Iterator<MetaData> iterator = MetaContainer.getBeanClasses(); MetaData metaData; ClassLoader newLoader; ClassLoader oldLoader = null; ClassLoader commonLoader = null; while (iterator.hasNext()) { metaData = iterator.next(); newLoader = metaData.getLoader(); if (ObjectUtils.notNull(oldLoader) && ObjectUtils.notNull(newLoader)) { commonLoader = LibraryLoader.createCommon(newLoader, oldLoader); } oldLoader = newLoader; } return commonLoader; } /** * Reloads {@link RestConfig} instance with new registered * {@link org.glassfish.jersey.server.model.Resource}s to activate */ public static void reload() { try { RestReloader reloader = RestReloader.get(); RestConfig conf = get(); if (ObjectUtils.notNull(conf) && ObjectUtils.notNull(reloader)) { if (RestContainer.hasRest()) { RestConfig existingConfig = RestContainer.getRestConfig(); Set<Resource> existingResources = existingConfig .getResources(); RestContainer.removeResources(existingResources); } ClassLoader commonLoader = getCommonLoader(); if (ObjectUtils.notNull(commonLoader)) { conf.setClassLoader(commonLoader); } conf.registerPreResources(); reloader.reload(conf); conf.cache(); } } finally { newConfig = null; } } }
package org.lightmare.utils.rest; import java.lang.reflect.Method; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import org.lightmare.cache.RestContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.ObjectUtils; /** * Class to check if {@link Class} is annotated for jax.rs appropriated REST * annotations and valid to create * {@link org.glassfish.jersey.server.model.Resource} classes * * @author Levan Tsinadze * @since 0.0.74-SNAPSHOT */ public class RestCheck { public static final String PATH_CLASS_NAME = "javax.ws.rs.Path"; /** * Checks and caches if libraries has {@link Path} class file to load it * * @author Levan Tsinadze * */ private static enum PathChecks { CHECK; final boolean value; private PathChecks() { value = LibraryLoader.isClass(PATH_CLASS_NAME); } } /** * Reloads REST service */ public static void reload() { if (RestContainer.hasRest()) { RestProvider.reload(); } } /** * Checks annotations on {@link Class} and its {@link Method}s for REST * resources * * @param method * @return <code>boolean</code> */ private static boolean checkAnnotation(Method method) { boolean valid = (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class) || method.isAnnotationPresent(PUT.class) || method .isAnnotationPresent(DELETE.class)); return valid; } /** * Checks if passed {@link Class} is available to create * {@link org.glassfish.jersey.server.model.Resource} instance * * @param resourceClass * @return <code>boolean</code> */ public static boolean check(Class<?> resourceClass) { boolean valid = PathChecks.CHECK.value; if (valid) { valid = ObjectUtils.notNull(resourceClass) && resourceClass.isAnnotationPresent(Path.class); if (valid) { Method[] methods = resourceClass.getDeclaredMethods(); int length = methods.length; Method method; for (int i = 0; i < length && ObjectUtils.notTrue(valid); i++) { method = methods[i]; valid = checkAnnotation(method); } } } return valid; } }
package com.proxerme.library.connection.experimental.messages.entity; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import com.afollestad.bridge.annotations.Body; import com.proxerme.library.interfaces.IdItem; import com.proxerme.library.interfaces.ImageItem; import com.proxerme.library.interfaces.TimeItem; /** * Entity holding all relevant information about a Conference. * * @author Ruben Gees */ public class Conference implements Parcelable, IdItem, TimeItem, ImageItem { public static final Parcelable.Creator<Conference> CREATOR = new Parcelable.Creator<Conference>() { public Conference createFromParcel(Parcel source) { return new Conference(source); } public Conference[] newArray(int size) { return new Conference[size]; } }; @Body(name = "id") String id; @Body(name = "topic") String topic; @Body(name = "count") int participantAmount; @Body(name = "conference") boolean isConference; @Body(name = "timestamp_end") long time; @Body(name = "read") byte isRead; @Body(name = "image") String imageId; Conference() { } /** * @param id The id of the Conference. * @param topic The topic. * @param participantAmount The amount of participants. * @param isConference Indicator, if this Conference has more than 2 participants. * (group conversation) * @param time The time of the last message. * @param isRead Indicator, if the user has isRead the last message in this Conference. * @param imageId The id of the image. */ public Conference(@NonNull String id, @NonNull String topic, int participantAmount, boolean isConference, long time, boolean isRead, @NonNull String imageId) { this.id = id; this.topic = topic; this.participantAmount = participantAmount; this.isConference = isConference; this.time = time; this.isRead = (byte) (isRead ? 1 : 0); this.imageId = imageId; } protected Conference(Parcel in) { this.id = in.readString(); this.topic = in.readString(); this.participantAmount = in.readInt(); this.isConference = in.readByte() != 0; this.time = in.readLong(); this.isRead = in.readByte(); this.imageId = in.readString(); } /** * Returns the id of this Conference. * @return The id. */ @NonNull @Override public String getId() { return id; } /** * Returns the topic of this Conference. * @return The topic. */ @NonNull public String getTopic() { return topic; } /** * Returns the amount of participants in this Conference. * @return The amount of participants. */ @IntRange(from = 2) public int getParticipantAmount() { return participantAmount; } /** * Returns if this Conference is a group conversation. * @return Returns true if this isConference has more than 2 participants. */ public boolean isConference() { return isConference; } /** * Returns the time of the last message. * @return The time. */ @Override public long getTime() { return time; } /** * Returns if the user has isRead the last message in this isConference. * @return True if the user has isRead the last message. */ public boolean isRead() { return isRead == 1; } /** * Returns the id of this image of the Conference. May be and empty string, if this isConference * has no image. (Users without a profile image and group conversation) * @return The id. */ @NonNull @Override public String getImageId() { return imageId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Conference that = (Conference) o; if (participantAmount != that.participantAmount) return false; if (isConference != that.isConference) return false; if (time != that.time) return false; if (isRead != that.isRead) return false; if (!id.equals(that.id)) return false; if (!topic.equals(that.topic)) return false; return imageId.equals(that.imageId); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + topic.hashCode(); result = 31 * result + participantAmount; result = 31 * result + (isConference ? 1 : 0); result = 31 * result + (int) (time ^ (time >>> 32)); result = 31 * result + (int) isRead; result = 31 * result + imageId.hashCode(); return result; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.topic); dest.writeInt(this.participantAmount); dest.writeByte(isConference ? (byte) 1 : (byte) 0); dest.writeLong(this.time); dest.writeByte(this.isRead); dest.writeString(this.imageId); } }
package org.parboiled.transform; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.BasicValue; import org.parboiled.BaseParser; import org.parboiled.support.Var; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.objectweb.asm.Opcodes.ARETURN; import static org.objectweb.asm.Opcodes.INVOKESPECIAL; import static org.objectweb.asm.Opcodes.INVOKESTATIC; import static org.parboiled.transform.AsmUtils.getClassForType; import static org.parboiled.transform.AsmUtils.isActionRoot; import static org.parboiled.transform.AsmUtils.isAssignableTo; import static org.parboiled.transform.AsmUtils.isBooleanValueOfZ; import static org.parboiled.transform.AsmUtils.isVarRoot; public class RuleMethod extends MethodNode { private final List<InstructionGroup> groups = new ArrayList<InstructionGroup>(); private final List<LabelNode> usedLabels = new ArrayList<LabelNode>(); private final Class<?> ownerClass; private final int parameterCount; private boolean containsImplicitActions; // calls to Boolean.valueOf(boolean) private boolean containsExplicitActions; // calls to BaseParser.ACTION(boolean) private boolean containsVars; // calls to Var.<init>(T) private boolean containsPotentialSuperCalls; private boolean hasDontExtend; private boolean hasExplicitActionOnlyAnnotation; private boolean hasCachedAnnotation; private boolean hasDontLabelAnnotation; private boolean hasSuppressNodeAnnotation; private boolean hasSuppressSubnodesAnnotation; private boolean hasSkipNodeAnnotation; private boolean hasMemoMismatchesAnnotation; private boolean hasSkipActionsInPredicatesAnnotation; private int numberOfReturns; private InstructionGraphNode returnInstructionNode; private List<InstructionGraphNode> graphNodes; private List<LocalVariableNode> localVarVariables; private boolean bodyRewritten; private boolean skipGeneration; public RuleMethod(final Class<?> ownerClass, final int access, final String name, final String desc, final String signature, final String[] exceptions, final boolean hasExplicitActionOnlyAnno, final boolean hasDontLabelAnno, final boolean hasSkipActionsInPredicates) { super(Opcodes.ASM4, access, name, desc, signature, exceptions); this.ownerClass = ownerClass; parameterCount = Type.getArgumentTypes(desc).length; hasCachedAnnotation = parameterCount == 0; hasDontLabelAnnotation = hasDontLabelAnno; hasExplicitActionOnlyAnnotation = hasExplicitActionOnlyAnno; hasSkipActionsInPredicatesAnnotation = hasSkipActionsInPredicates; skipGeneration = isSuperMethod(); } public List<InstructionGroup> getGroups() { return groups; } public List<LabelNode> getUsedLabels() { return usedLabels; } public Class<?> getOwnerClass() { return ownerClass; } public boolean hasDontExtend() { return hasDontExtend; } public int getParameterCount() { return parameterCount; } public boolean containsImplicitActions() { return containsImplicitActions; } public void setContainsImplicitActions(final boolean containsImplicitActions) { this.containsImplicitActions = containsImplicitActions; } public boolean containsExplicitActions() { return containsExplicitActions; } public void setContainsExplicitActions(final boolean containsExplicitActions) { this.containsExplicitActions = containsExplicitActions; } public boolean containsVars() { return containsVars; } public boolean containsPotentialSuperCalls() { return containsPotentialSuperCalls; } public boolean hasCachedAnnotation() { return hasCachedAnnotation; } public boolean hasDontLabelAnnotation() { return hasDontLabelAnnotation; } public boolean hasSuppressNodeAnnotation() { return hasSuppressNodeAnnotation; } public boolean hasSuppressSubnodesAnnotation() { return hasSuppressSubnodesAnnotation; } public boolean hasSkipActionsInPredicatesAnnotation() { return hasSkipActionsInPredicatesAnnotation; } public boolean hasSkipNodeAnnotation() { return hasSkipNodeAnnotation; } public boolean hasMemoMismatchesAnnotation() { return hasMemoMismatchesAnnotation; } public int getNumberOfReturns() { return numberOfReturns; } public InstructionGraphNode getReturnInstructionNode() { return returnInstructionNode; } public void setReturnInstructionNode(final InstructionGraphNode returnInstructionNode) { this.returnInstructionNode = returnInstructionNode; } public List<InstructionGraphNode> getGraphNodes() { return graphNodes; } public List<LocalVariableNode> getLocalVarVariables() { return localVarVariables; } public boolean isBodyRewritten() { return bodyRewritten; } public void setBodyRewritten() { this.bodyRewritten = true; } public boolean isSuperMethod() { Preconditions.checkState(!name.isEmpty()); return name.charAt(0) == '$'; } public InstructionGraphNode setGraphNode(final AbstractInsnNode insn, final BasicValue resultValue, final List<BasicValue> predecessors) { if (graphNodes == null) { // initialize with a list of null values graphNodes = Lists.newArrayList( new InstructionGraphNode[instructions.size()]); } final int index = instructions.indexOf(insn); InstructionGraphNode node = graphNodes.get(index); if (node == null) { node = new InstructionGraphNode(insn, resultValue); graphNodes.set(index, node); } node.addPredecessors(predecessors); return node; } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { if (Types.EXPLICIT_ACTIONS_ONLY_DESC.equals(desc)) { hasExplicitActionOnlyAnnotation = true; return null; // we do not need to record this annotation } if (Types.CACHED_DESC.equals(desc)) { hasCachedAnnotation = true; return null; // we do not need to record this annotation } if (Types.SUPPRESS_NODE_DESC.equals(desc)) { hasSuppressNodeAnnotation = true; return null; // we do not need to record this annotation } if (Types.SUPPRESS_SUBNODES_DESC.equals(desc)) { hasSuppressSubnodesAnnotation = true; return null; // we do not need to record this annotation } if (Types.SKIP_NODE_DESC.equals(desc)) { hasSkipNodeAnnotation = true; return null; // we do not need to record this annotation } if (Types.MEMO_MISMATCHES_DESC.equals(desc)) { hasMemoMismatchesAnnotation = true; return null; // we do not need to record this annotation } if (Types.SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = true; return null; // we do not need to record this annotation } if (Types.DONT_SKIP_ACTIONS_IN_PREDICATES_DESC.equals(desc)) { hasSkipActionsInPredicatesAnnotation = false; return null; // we do not need to record this annotation } if (Types.DONT_LABEL_DESC.equals(desc)) { hasDontLabelAnnotation = true; return null; // we do not need to record this annotation } if (Types.DONT_EXTEND_DESC.equals(desc)) { hasDontExtend = true; return null; // we do not need to record this annotation } return visible ? super.visitAnnotation(desc, true) : null; // only keep visible annotations } @Override public void visitMethodInsn( final int opcode, final String owner, final String name, final String desc) { switch (opcode) { case INVOKESTATIC: if (!hasExplicitActionOnlyAnnotation && isBooleanValueOfZ(owner, name, desc)) { containsImplicitActions = true; } else if (isActionRoot(owner, name)) { containsExplicitActions = true; } break; case INVOKESPECIAL: if ("<init>".equals(name)) { if (isVarRoot(owner, name, desc)) { containsVars = true; } } else if (isAssignableTo(owner, BaseParser.class)) { containsPotentialSuperCalls = true; } break; } super.visitMethodInsn(opcode, owner, name, desc); } @Override public void visitInsn(final int opcode) { if (opcode == ARETURN) numberOfReturns++; super.visitInsn(opcode); } @Override public void visitJumpInsn(final int opcode, final Label label) { usedLabels.add(getLabelNode(label)); super.visitJumpInsn(opcode, label); } @Override public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitTableSwitchInsn(min, max, dflt, labels); } @Override public void visitLookupSwitchInsn( final Label dflt, final int[] keys, final Label[] labels) { usedLabels.add(getLabelNode(dflt)); for (final Label label : labels) usedLabels.add(getLabelNode(label)); super.visitLookupSwitchInsn(dflt, keys, labels); } @Override public void visitLineNumber(final int line, final Label start) { // do not record line numbers } @Override public void visitLocalVariable( final String name, final String desc, final String signature, final Label start, final Label end, final int index) { // only remember the local variables of Type org.parboiled.support.Var that are not parameters if (index > parameterCount && Var.class.isAssignableFrom(getClassForType(Type.getType(desc)))) { if (localVarVariables == null) localVarVariables = new ArrayList<LocalVariableNode>(); localVarVariables.add(new LocalVariableNode(name, desc, null, null, null, index)); } } @Override public String toString() { return name; } public void moveFlagsTo(final RuleMethod overridingMethod) { Preconditions.checkNotNull(overridingMethod, "overridingMethod"); overridingMethod.hasCachedAnnotation |= hasCachedAnnotation; overridingMethod.hasDontLabelAnnotation |= hasDontLabelAnnotation; overridingMethod.hasSuppressNodeAnnotation |= hasSuppressNodeAnnotation; overridingMethod.hasSuppressSubnodesAnnotation |= hasSuppressSubnodesAnnotation; overridingMethod.hasSkipNodeAnnotation |= hasSkipNodeAnnotation; overridingMethod.hasMemoMismatchesAnnotation |= hasMemoMismatchesAnnotation; hasCachedAnnotation = false; hasDontLabelAnnotation = true; hasSuppressNodeAnnotation = false; hasSuppressSubnodesAnnotation = false; hasSkipNodeAnnotation = false; hasMemoMismatchesAnnotation = false; } public boolean isGenerationSkipped() { return skipGeneration; } public void dontSkipGeneration() { skipGeneration = false; } public void suppressNode() { hasSuppressNodeAnnotation = true; } }
package gui; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import server.Server; import server.ServerFactory; public class CreateServerListener implements ActionListener{ private JTextField tfPort; private JLabel fail; private Server s; private JFrame frame; public CreateServerListener(JTextField tfPort, JLabel fail, Server s, JFrame frame) { this.tfPort = tfPort; this.fail = fail; this.s = s; this.frame = frame; } @Override public void actionPerformed(ActionEvent arg0) { int iport = -1; try{ iport = Integer.parseInt(tfPort.getText()); fail.setVisible(false); s = ServerFactory.createServer(iport); new StartUpThread(s).start(); createNewGui(); } catch (NumberFormatException nfe) { fail.setText("Please insert a real number for the Port"); fail.setVisible(true); } } /** * @wbp.parser.entryPoint */ private void createNewGui() { /*Delete*/ /*Delete*/
package com.quickblox.qmunicate.ui.main; import android.database.Cursor; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FilterQueryProvider; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; import com.quickblox.qmunicate.App; import com.quickblox.qmunicate.R; import com.quickblox.qmunicate.caching.DatabaseManager; import com.quickblox.qmunicate.core.command.Command; import com.quickblox.qmunicate.model.Friend; import com.quickblox.qmunicate.qb.commands.QBAddFriendCommand; import com.quickblox.qmunicate.qb.commands.QBFriendsLoadCommand; import com.quickblox.qmunicate.qb.commands.QBUserSearchCommand; import com.quickblox.qmunicate.service.QBServiceConsts; import com.quickblox.qmunicate.ui.base.BaseFragment; import com.quickblox.qmunicate.ui.friend.FriendDetailsActivity; import com.quickblox.qmunicate.utils.Consts; import com.quickblox.qmunicate.utils.DialogUtils; import com.quickblox.qmunicate.utils.ErrorUtils; import com.quickblox.qmunicate.utils.PrefsHelper; import java.util.ArrayList; import java.util.List; import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh; import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout; import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; public class FriendsListFragment extends BaseFragment implements AdapterView.OnItemClickListener, OnRefreshListener, SearchView.OnQueryTextListener, FilterQueryProvider { private List<Friend> usersList; private UserListAdapter usersListAdapter; private LinearLayout globalSearchLayout; private State state; private String constraint; private boolean isImportInitialized; private boolean inNeedToInitFriendsList; private ListView friendsListView; private TextView friendsTitle; private View friendsListViewTitle; private BaseAdapter friendsListAdapter; private PullToRefreshLayout pullToRefreshLayout; private int headersAndFootersCounter; public static FriendsListFragment newInstance() { return new FriendsListFragment(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); addActionsAddFriend(); setHasOptionsMenu(true); } private void addActionsAddFriend() { baseActivity.addAction(QBServiceConsts.ADD_FRIEND_SUCCESS_ACTION, new AddFriendSuccessAction()); baseActivity.addAction(QBServiceConsts.ADD_FRIEND_FAIL_ACTION, failAction); baseActivity.addAction(QBServiceConsts.FRIENDS_LOAD_SUCCESS_ACTION, new FriendsLoadSuccessAction()); baseActivity.addAction(QBServiceConsts.FRIENDS_LOAD_FAIL_ACTION, failAction); baseActivity.addAction(QBServiceConsts.USER_SEARCH_SUCCESS_ACTION, new UserSearchSuccessAction()); baseActivity.addAction(QBServiceConsts.USER_SEARCH_FAIL_ACTION, new UserSearchFailAction()); baseActivity.updateBroadcastActionList(); } @Override public void onResume() { super.onResume(); startFriendsListLoader(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.friend_list_menu, menu); MenuItem searchItem = menu.findItem(R.id.action_search); searchItem.setOnActionExpandListener(new SearchOnActionExpandListener()); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; default: return super.onOptionsItemSelected(item); } } private void startFriendsListLoader() { QBFriendsLoadCommand.start(baseActivity); } @Override public Cursor runQuery(CharSequence constraint) { return DatabaseManager.fetchFriendsByFullname(baseActivity, constraint.toString()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); title = getString(R.string.nvd_title_friends); state = State.FRIENDS_LIST; } @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { View rootView = layoutInflater.inflate(R.layout.fragment_friend_list, container, false); isImportInitialized = App.getInstance().getPrefsHelper().getPref(PrefsHelper.PREF_IMPORT_INITIALIZED, false); headersAndFootersCounter++; initUI(rootView, layoutInflater); initGlobalSearchButton(layoutInflater); initPullToRefresh(rootView); updateFriendsList(); return rootView; } private void initUI(View view, LayoutInflater layoutInflater) { friendsListView = (ListView) view.findViewById(R.id.friendList); friendsListViewTitle = layoutInflater.inflate(R.layout.view_section_title_friends_list, null); friendsTitle = (TextView) friendsListViewTitle.findViewById(R.id.listTitle); } private void initGlobalSearchButton(LayoutInflater inflater) { globalSearchLayout = (LinearLayout) inflater.inflate(R.layout.view_global_search_button, null); globalSearchLayout.findViewById(R.id.globalSearchButton).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { startGlobalSearch(); } } ); } private void initPullToRefresh(View view) { pullToRefreshLayout = (PullToRefreshLayout) view.findViewById(R.id.pullToRefreshLayout); ActionBarPullToRefresh.from(baseActivity).allChildrenArePullable().listener(this).setup( pullToRefreshLayout); } private void updateFriendsList() { friendsTitle.setVisibility(View.GONE); friendsListAdapter = new FriendsListCursorAdapter(baseActivity, getAllFriends()); friendsListView.addHeaderView(friendsListViewTitle); friendsListView.setAdapter(friendsListAdapter); friendsListView.setSelector(R.drawable.list_item_background_selector); friendsListView.setOnItemClickListener(this); } private void startGlobalSearch() { inNeedToInitFriendsList = true; state = State.GLOBAL_LIST; friendsTitle.setText(R.string.frl_all_users); hideGlobalSearchButton(); initUserList(); } private Cursor getAllFriends() { return DatabaseManager.getAllFriends(baseActivity); } private void hideGlobalSearchButton() { if (friendsListView != null) { friendsListView.removeFooterView(globalSearchLayout); } } private void initUserList() { usersList = new ArrayList<Friend>(); usersListAdapter = new UserListAdapter(baseActivity, usersList, new UserListAdapter.UserListListener() { @Override public void onUserSelected(int position) { addToFriendList(usersList.get(position)); } } ); friendsListView.setSelector(android.R.color.transparent); friendsListView.setAdapter(usersListAdapter); friendsListView.setOnItemClickListener(null); startUsersListLoader(constraint); } private void addToFriendList(final Friend friend) { baseActivity.showProgress(); QBAddFriendCommand.start(baseActivity, friend); } private void startUsersListLoader(String newText) { QBUserSearchCommand.start(baseActivity, newText); usersListAdapter.setSearchCharacters(newText); } @Override public void onStart() { super.onStart(); if (!isImportInitialized) { addActionsAddFriends(); } } private void addActionsAddFriends() { baseActivity.addAction(QBServiceConsts.ADD_FRIENDS_SUCCESS_ACTION, new AddFriendsSuccessAction()); baseActivity.addAction(QBServiceConsts.ADD_FRIENDS_FAIL_ACTION, new AddFriendsFailAction()); baseActivity.updateBroadcastActionList(); } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { constraint = newText; if (state == State.FRIENDS_LIST) { FriendsListCursorAdapter friendListCursorAdapter = (FriendsListCursorAdapter) friendsListAdapter; friendListCursorAdapter.setFilterQueryProvider(this); friendListCursorAdapter.getFilter().filter(newText); friendListCursorAdapter.setSearchCharacters(newText); } else { startUsersListLoader(newText); } return true; } @Override public void onRefreshStarted(View view) { startFriendsListLoader(); } @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if (position == Consts.ZERO_VALUE) { return; } Cursor selectedItem = (Cursor) friendsListAdapter.getItem(position - headersAndFootersCounter); FriendDetailsActivity.start(baseActivity, DatabaseManager.getFriendFromCursor(selectedItem)); } private void updateUsersList(List<Friend> friendsList) { usersList.clear(); usersList.addAll(friendsList); usersListAdapter.notifyDataSetChanged(); } private void showGlobalSearchButton() { friendsListView.addFooterView(globalSearchLayout); } private void saveFriendToCache(Friend friend) { DatabaseManager.saveFriend(baseActivity, friend); } private void importFriendsFinished() { App.getInstance().getPrefsHelper().savePref(PrefsHelper.PREF_IMPORT_INITIALIZED, true); startFriendsListLoader(); baseActivity.hideProgress(); } private void updateFriends(List<Friend> friendsList) { clearCachedFriends(); saveFriendsToCache(friendsList); } private void clearCachedFriends() { DatabaseManager.deleteAllFriends(baseActivity); } private void saveFriendsToCache(List<Friend> friendsList) { DatabaseManager.saveFriends(baseActivity, friendsList); } private enum State {FRIENDS_LIST, GLOBAL_LIST} private class SearchOnActionExpandListener implements MenuItem.OnActionExpandListener { @Override public boolean onMenuItemActionExpand(MenuItem item) { showGlobalSearchButton(); friendsTitle.setVisibility(View.VISIBLE); friendsTitle.setText(R.string.frl_friends); inNeedToInitFriendsList = false; return true; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { hideGlobalSearchButton(); state = State.FRIENDS_LIST; if (friendsTitle != null) { friendsTitle.setVisibility(View.GONE); } if (inNeedToInitFriendsList) { inNeedToInitFriendsList = false; updateFriendsList(); } baseActivity.getActionBar().setDisplayShowHomeEnabled(true); return true; } } private class AddFriendSuccessAction implements Command { @Override public void execute(Bundle bundle) { Friend friend = (Friend) bundle.getSerializable(QBServiceConsts.EXTRA_FRIEND); saveFriendToCache(friend); usersListAdapter.notifyDataSetChanged(); baseActivity.hideProgress(); } } private class FriendsLoadSuccessAction implements Command { @Override public void execute(Bundle bundle) { List<Friend> friendsList = (List<Friend>) bundle.getSerializable(QBServiceConsts.EXTRA_FRIENDS); updateFriends(friendsList); pullToRefreshLayout.setRefreshComplete(); } } private class UserSearchSuccessAction implements Command { @Override public void execute(Bundle bundle) { List<Friend> friendsList = (List<Friend>) bundle.getSerializable(QBServiceConsts.EXTRA_FRIENDS); updateUsersList(friendsList); } } private class UserSearchFailAction implements Command { @Override public void execute(Bundle bundle) { Exception e = (Exception) bundle.getSerializable(QBServiceConsts.EXTRA_ERROR); ErrorUtils.showError(baseActivity, e); } } private class AddFriendsSuccessAction implements Command { @Override public void execute(Bundle bundle) { importFriendsFinished(); } } private class AddFriendsFailAction implements Command { @Override public void execute(Bundle bundle) { importFriendsFinished(); DialogUtils.show(baseActivity, getResources().getString(R.string.dlg_no_friends_for_import)); } } }
package org.scijava.command; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.scijava.event.EventService; import org.scijava.module.Module; import org.scijava.module.ModuleService; import org.scijava.module.process.PostprocessorPlugin; import org.scijava.module.process.PreprocessorPlugin; import org.scijava.plugin.PTService; import org.scijava.plugin.PluginInfo; import org.scijava.plugin.PluginService; import org.scijava.plugin.SciJavaPlugin; import org.scijava.service.SciJavaService; /** * Interface for service that keeps track of available commands. * <p> * A <em>command</em> is a particular type of plugin that is also a * {@link Module}; i.e., it is {@link Runnable}, with typed inputs and outputs. * <p> * The command service keeps a master index of all commands known to the system. * It asks the {@link PluginService} for available commands, then takes care of * registering them with the {@link ModuleService}. * </p> * * @author Curtis Rueden * @see SciJavaPlugin * @see ModuleService * @see PluginService */ public interface CommandService extends PTService<Command>, SciJavaService { EventService getEventService(); ModuleService getModuleService(); /** Gets the list of all available {@link Command}s). */ List<CommandInfo> getCommands(); /** Gets the list of {@link Command}s corresponding to the given plugins. */ <CT extends Command> List<CommandInfo> getCommands( final List<PluginInfo<CT>> plugins); /** Gets the first available command of the given class, or null if none. */ <C extends Command> CommandInfo getCommand(Class<C> commandClass); /** * Gets the first available command of the given class name, or null if none. */ CommandInfo getCommand(String className); /** Gets the list of {@link Command}s of the given type. */ <CT extends Command> List<CommandInfo> getCommandsOfType(Class<CT> type); /** * Gets the list of commands of the given class. * <p> * Most classes will have only a single match, but some special classes (such * as ImageJ's {@code LegacyCommand}) may match many entries. * </p> */ <C extends Command> List<CommandInfo> getCommandsOfClass( Class<C> commandClass); /** * Gets the list of commands with the given class name. * <p> * Most classes will have only a single match, but some special classes (such * as ImageJ's {@code LegacyCommand}) may match many entries. * </p> */ List<CommandInfo> getCommandsOfClass(String className); /** * Executes the first command of the given class name. * <p> * If no command with the given class name is registered with the service, * then a default one is created and then executed. This default command is * <em>not</em> registered with the service for subsequent usage. * </p> * * @param className Class name of the command to execute. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the plugin, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<CommandModule> run(String className, boolean process, Object... inputs); /** * Executes the first command of the given class name. * <p> * If no command with the given class name is registered with the service, * then a default one is created and then executed. This default command is * <em>not</em> registered with the service for subsequent usage. * </p> * * @param className Class name of the command to execute. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputMap Table of input parameter values, with keys matching the * plugin's input parameter names. Passing a value of a type * incompatible with the associated input parameter will issue an * error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<CommandModule> run(String className, boolean process, Map<String, Object> inputMap); /** * Executes the first command of the given class. * <p> * If no command of the given class is registered with the service, then a * default one is created and then executed. This default command is * <em>not</em> registered with the service for subsequent usage. * </p> * * @param <C> Class of the command to execute. * @param commandClass Class object of the command to execute. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the plugin, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <C extends Command> Future<CommandModule> run(Class<C> commandClass, boolean process, Object... inputs); /** * Executes the first command of the given class. * <p> * If no command of the given class is registered with the service, then a * default one is created and then executed. This default command is * <em>not</em> registered with the service for subsequent usage. * </p> * * @param <C> Class of the command to execute. * @param commandClass Class object of the command to execute. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputMap Table of input parameter values, with keys matching the * plugin's input parameter names. Passing a value of a type * incompatible with the associated input parameter will issue an * error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <C extends Command> Future<CommandModule> run(Class<C> commandClass, boolean process, Map<String, Object> inputMap); /** * Executes the given command. * * @param info The command to instantiate and run. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the plugin, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<CommandModule> run(CommandInfo info, boolean process, Object... inputs); /** * Executes the given command. * * @param info The command to instantiate and run. * @param process If true, executes the command with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the command with no pre- or postprocessing. For more * fine-grained control, see the {@link ModuleService#run} methods. * @param inputMap Table of input parameter values, with keys matching the * plugin's input parameter names. Passing a value of a type * incompatible with the associated input parameter will issue an * error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<CommandModule> run(CommandInfo info, boolean process, Map<String, Object> inputMap); }
package org.smoothbuild.parse; import static org.smoothbuild.parse.AssignArgsToParams.assignArgsToParams; import static org.smoothbuild.parse.AssignNatives.assignNatives; import static org.smoothbuild.parse.ConstructorLoader.loadConstructor; import static org.smoothbuild.parse.FindNatives.findNatives; import static org.smoothbuild.parse.FindSemanticErrors.findSemanticErrors; import static org.smoothbuild.parse.ScriptParser.parseScript; import static org.smoothbuild.util.Lists.list; import static org.smoothbuild.util.Paths.changeExtension; import java.nio.file.Path; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.smoothbuild.antlr.SmoothParser.ModuleContext; import org.smoothbuild.lang.function.Native; import org.smoothbuild.lang.runtime.SRuntime; import org.smoothbuild.parse.ast.Ast; import org.smoothbuild.parse.ast.AstCreator; import org.smoothbuild.parse.ast.FuncNode; import org.smoothbuild.parse.ast.StructNode; import org.smoothbuild.util.Maybe; public class ModuleLoader { private final SRuntime runtime; private final AssignTypes assignTypes; private final FunctionLoader functionLoader; @Inject public ModuleLoader(SRuntime runtime, AssignTypes assignTypes, FunctionLoader functionLoader) { this.runtime = runtime; this.assignTypes = assignTypes; this.functionLoader = functionLoader; } public List<? extends Object> loadModule(Path script) { Maybe<ModuleContext> maybeModule = parseScript(script); if (!maybeModule.hasValue()) { return maybeModule.errors(); } Ast ast = AstCreator.fromParseTree(script, maybeModule.value()); List<? extends Object> errors = findSemanticErrors(runtime, ast); if (!errors.isEmpty()) { return errors; } errors = ast.sortFuncsByDependencies(runtime.functions()); if (!errors.isEmpty()) { return errors; } errors = ast.sortTypesByDependencies(runtime.types()); if (!errors.isEmpty()) { return errors; } errors = assignTypes.assignTypes(runtime.functions(), ast); if (!errors.isEmpty()) { return errors; } errors = assignArgsToParams(runtime.functions(), ast); if (!errors.isEmpty()) { return errors; } Maybe<Map<String, Native>> maybeNatives = findNatives(changeExtension(script, "jar")); if (!maybeNatives.hasValue()) { return maybeNatives.errors(); } Map<String, Native> natives = maybeNatives.value(); errors = assignNatives(ast, natives); if (!errors.isEmpty()) { return errors; } loadFunctions(ast); return list(); } private void loadFunctions(Ast ast) { for (StructNode struct : ast.structs()) { runtime.functions().add(loadConstructor(struct)); } for (FuncNode func : ast.funcs()) { runtime.functions().add(functionLoader.loadFunction(runtime.functions(), func)); } } }
package org.trancecode.xml.saxon; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.Collection; import java.util.Iterator; import net.sf.saxon.s9api.Axis; import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.s9api.XdmNode; import org.trancecode.function.TcPredicates; /** * Utility methods to retrieve node sequences through axis in Saxon. * * @author Herve Quiroz */ public final class SaxonAxis { private SaxonAxis() { // No instantiation } public static Iterable<XdmNode> attributes(final XdmNode node) { return Iterables.filter(childNodes(node), SaxonPredicates.isAttribute()); } public static Iterable<XdmItem> axis(final XdmNode node, final Axis axis) { return new Iterable<XdmItem>() { @Override public Iterator<XdmItem> iterator() { return node.axisIterator(axis); } }; } public static XdmNode childElement(final XdmNode node) { return Iterables.getOnlyElement(childElements(node), null); } public static XdmNode childElement(final XdmNode node, final Collection<QName> elementNames) { return Iterables.getOnlyElement(childElements(node, elementNames), null); } public static XdmNode childElement(final XdmNode node, final QName... elementNames) { return childElement(node, ImmutableSet.copyOf(elementNames)); } public static Iterable<XdmNode> childElements(final XdmNode node) { return Iterables.filter(childNodes(node), SaxonPredicates.isElement()); } public static Iterable<XdmNode> childElements(final XdmNode node, final Collection<QName> elementNames) { return Iterables.filter(childElements(node), Predicates.compose(TcPredicates.matches(elementNames), SaxonFunctions.getNodeName())); } public static Iterable<XdmNode> childElements(final XdmNode node, final QName... elementNames) { return childElements(node, ImmutableSet.copyOf(elementNames)); } public static Iterable<XdmNode> childNodes(final XdmNode node) { return Iterables.filter(childXdmItems(node), XdmNode.class); } public static Iterable<XdmNode> childNodesNoAttributes(final XdmNode node) { return Iterables.filter(childNodes(node), Predicates.not(SaxonPredicates.isAttribute())); } public static Iterable<XdmItem> childXdmItems(final XdmNode node) { return Iterables.concat(axis(node, Axis.ATTRIBUTE), axis(node, Axis.CHILD)); } public static Iterable<XdmNode> namespaces(final XdmNode node) { return Iterables.filter(axis(node, Axis.NAMESPACE), XdmNode.class); } }
package org.wattdepot.dashboard; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.WriteResult; import org.wattdepot.client.http.api.WattDepotClient; import org.wattdepot.common.domainmodel.Depository; import org.wattdepot.common.domainmodel.DescriptiveStats; import org.wattdepot.common.domainmodel.InterpolatedValue; import org.wattdepot.common.domainmodel.InterpolatedValueList; import org.wattdepot.common.domainmodel.SensorGroup; import org.wattdepot.common.domainmodel.SensorStatusList; import org.wattdepot.common.exception.BadCredentialException; import org.wattdepot.common.exception.IdNotFoundException; import org.wattdepot.common.util.DateConvert; import org.wattdepot.common.util.tstamp.Tstamp; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.XMLGregorianCalendar; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; /** * DataBridge - The bridge between WattDepot and the Hale Aloha Dashboard DataBridgeMain. * * @author Cam Moore */ public class DataBridge { /** * The host name of the Mongo db. */ private static final String MONGODB_HOST = "localhost"; /** * The port number of the Mongo db. */ private static final int MONGODB_PORT = 27017; /** * The name of the Hale Aloha Dashboard database. */ private static final String DB_NAME = "hale_aloha"; /** * The power collection name. */ private static final String POWER = "power"; /** * The hourly energy collection name. */ private static final String HOURLY = "hourly"; /** * The daily energy collection name. */ private static final String DAILY = "daily"; /** * The predicted hourly energy collection name. */ private static final String PREDICTED_HOURLY = "predictedHourly"; /** * The predicted daily energy collection name. */ private static final String PREDICTED_DAILY = "predictedDaily"; /** * The sensor status collection name. */ private static final String STATUS = "status"; /** * The URL to the WattDepot server. */ private static final String SERVER_URL = "http://mopsa.ics.hawaii.edu:8192/"; /** * The WattDepot client name. */ private static final String CLIENT_NAME = "hale_aloha"; /** * The WattDepot client's password. */ private static final String CLIENT_PASSWORD = "dashboard1"; /** * The WattDepot client's organization. */ private static final String CLIENT_ORG = "uh"; /** * The name of the energy depository. */ private static final String ENERGY = "energy"; /** * The singleton instance. */ private static DataBridge instance; /** * The power collection. */ private DBCollection powerCollection; /** * The hourly data collection. */ private DBCollection hourlyCollection; /** * The daily data collection. */ private DBCollection dailyCollection; /** * The predicted hourly energy collection. */ private DBCollection predictedHourlyCollection; /** * The predicted daily energy collection. */ private DBCollection predictedDailyCollection; /** * The sensor status collection. */ private DBCollection statusCollection; /** * The connection to the Hale Aloha Dashboard MongoDB. */ private MongoClient mongoClient; /** * The database holding the dashboard data. */ private DB db; /** * The WattDepotClient. */ private WattDepotClient client; /** * The power depository. */ private Depository powerDepository; /** * The energy depository. */ private Depository energyDepository; /** * A list of the tower SensorGroups. */ private ArrayList<SensorGroup> towerList; /** * The houly power history for each tower. Should be updated hourly. */ private Map<SensorGroup, DescriptiveStats> powerHistory; private static Logger logger = Logger.getLogger("data_bridge"); /** * Creates a new DataBridge initializing the MongoDB and WattDepot clients. * * @throws UnknownHostException if there is a problem with the MongoDB client. * @throws BadCredentialException if there is a problem with the WattDepot client. */ private DataBridge() throws UnknownHostException, BadCredentialException, IdNotFoundException { this.mongoClient = new MongoClient(MONGODB_HOST, MONGODB_PORT); this.db = mongoClient.getDB(DB_NAME); this.powerCollection = db.getCollection(POWER); this.hourlyCollection = db.getCollection(HOURLY); this.dailyCollection = db.getCollection(DAILY); this.statusCollection = db.getCollection(STATUS); this.predictedHourlyCollection = db.getCollection(PREDICTED_HOURLY); this.predictedDailyCollection = db.getCollection(PREDICTED_DAILY); this.client = new WattDepotClient(SERVER_URL, CLIENT_NAME, CLIENT_ORG, CLIENT_PASSWORD); this.powerDepository = client.getDepository(POWER); this.energyDepository = client.getDepository(ENERGY); this.towerList = new ArrayList<SensorGroup>(); // Initialize the tower list. We only need to do this once. for (SensorGroup g : client.getSensorGroups().getGroups()) { if (g.getId().endsWith("-total")) { towerList.add(g); } } this.powerHistory = new HashMap<SensorGroup, DescriptiveStats>(); ConsoleHandler handler = new ConsoleHandler(); logger.addHandler(handler); logger.setLevel(Level.FINEST); initializeDailyEnergy(); initializeHourlyEnergy(); } /** * @return The singleton instance or null if there is a problem with the clients. */ public static DataBridge getInstance() { if (instance == null) { try { instance = new DataBridge(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (BadCredentialException e) { e.printStackTrace(); } catch (IdNotFoundException e) { e.printStackTrace(); } } return instance; } /** * Updates the Hale Aloha current power. Removes any old power information before inserting the latest value. * * @return The number of power updates sent to the dashboard. */ public Integer updateCurrentPower() { Integer ret = 0; for (SensorGroup group : towerList) { InterpolatedValue value = client.getLatestValue(powerDepository, group); BasicDBObject doc = buildPowerDBObject(value); BasicDBObject remove = new BasicDBObject("tower", IdHelper.niceifyTowerId(group.getId())); powerCollection.remove(remove); powerCollection.insert(doc); ret++; } return ret; } /** * Clears the database of all daily energy data and inserts 30 days worth of usage data and 7 days of predicted. */ public void initializeDailyEnergy() { clearDailyEnergy(); XMLGregorianCalendar now = Tstamp.makeTimestamp(); XMLGregorianCalendar thirtyDaysAgo = Tstamp.incrementDays(now, -30); XMLGregorianCalendar nextSeven = Tstamp.incrementDays(now, 6); // going to get historical data for today also. InterpolatedValueList data = null; ArrayList<BasicDBObject> objects = null; for (SensorGroup group : towerList) { logger.info("loading daily energy data for tower " + IdHelper.niceifyTowerId(group.getId())); // 30 days of historical usage data = getDailyEnergyData(group, thirtyDaysAgo, now); objects = buildDBFromInterpolatedValues(data); for (BasicDBObject doc : objects) { this.dailyCollection.insert(doc); } // Get next 7 day predictions List<XMLGregorianCalendar> times = Tstamp.getTimestampList(now, nextSeven, 24 * 60); if (times != null) { for (int i = 0; i < times.size(); i++) { XMLGregorianCalendar time = times.get(i); data = getHistoricalDailyEnergyData(group, time, 7); BasicDBObject histObj = buildDailyHistoryDBObject(data); this.predictedDailyCollection.insert(histObj); } } } } /** * Updates the daily energy and history for each tower. * * @return The number of entries sent to the Hale Aloha Dashboard. */ public void updateDailyEnergy() { XMLGregorianCalendar now = Tstamp.makeTimestamp(); InterpolatedValueList data = null; ArrayList<BasicDBObject> objects = null; for (SensorGroup group : towerList) { BasicDBObject find = new BasicDBObject("tower", IdHelper.niceifyTowerId(group.getId())); DBObject mostRecent = null; for (DBObject rec : this.dailyCollection.find(find)) { if (mostRecent == null) { mostRecent = rec; } else if (((Date) mostRecent.get("date")).getTime() < ((Date) rec.get("date")).getTime()) { mostRecent = rec; } } try { XMLGregorianCalendar last = DateConvert.convertDate(((Date) mostRecent.get("date"))); data = getDailyEnergyData(group, last, now); objects = buildDBFromInterpolatedValues(data); logger.info(IdHelper.niceifyTowerId(group.getId()) + ": " + objects.size() + " records added"); for (BasicDBObject doc : objects) { this.dailyCollection.insert(doc); } // do we need to create prediction? for (InterpolatedValue value : data.getInterpolatedValues()) { XMLGregorianCalendar time = DateConvert.convertDate(value.getStart()); logger.info("prediction for " + time + " made"); InterpolatedValueList histData = getHistoricalDailyEnergyData(group, time, 7); BasicDBObject histObj = buildDailyHistoryDBObject(histData); this.predictedDailyCollection.insert(histObj); } } catch (DatatypeConfigurationException e) { e.printStackTrace(); } } } /** * Removes all the daily energy data from the database. * * @return The number of entries removed. */ private Integer clearDailyEnergy() { Integer integer = null; for (SensorGroup group : towerList) { logger.info("clearing daily data for " + IdHelper.niceifyTowerId(group.getId())); BasicDBObject remove = new BasicDBObject("tower", IdHelper.niceifyTowerId(group.getId())); WriteResult result = this.dailyCollection.remove(remove); if (integer == null) { integer = new Integer(0); } integer += result.getN(); this.predictedDailyCollection.remove(remove); } return integer; } /** * Initializes the hourly energy data, both the historical usage and the predicted usage for 24 hours. */ public void initializeHourlyEnergy() { clearHourlyEnergy(); XMLGregorianCalendar now = Tstamp.makeTimestamp(); XMLGregorianCalendar oneDayAgo = Tstamp.incrementDays(now, -1); XMLGregorianCalendar nextDay = Tstamp.incrementDays(now, 1); InterpolatedValueList data = null; ArrayList<BasicDBObject> objects = null; for (SensorGroup group : towerList) { logger.info("loading hourly energy data for tower " + IdHelper.niceifyTowerId(group.getId())); data = getHourlyEnergyData(group, oneDayAgo, now); objects = buildDBFromInterpolatedValues(data); for (BasicDBObject doc : objects) { this.hourlyCollection.insert(doc); } // get the prediction for the next 24 hours List<XMLGregorianCalendar> times = Tstamp.getTimestampList(now, nextDay, 60); if (times != null) { for (int i = 1; i < times.size(); i++) { XMLGregorianCalendar time = times.get(i); data = getHistoricalHourlyEnergyData(group, time, 7); BasicDBObject histObj = buildHourlyHistoryDBObject(data); this.predictedHourlyCollection.insert(histObj); } } } } /** * Updates the hourly energy, returning the number of entries added to the Hale Aloha Dashboard. * * @return The number of entries added to the Hale Aloha Dashboard. */ public void updateHourlyEnergy() { XMLGregorianCalendar now = Tstamp.makeTimestamp(); InterpolatedValueList data = null; ArrayList<BasicDBObject> objects = null; for (SensorGroup group : towerList) { BasicDBObject find = new BasicDBObject("tower", IdHelper.niceifyTowerId(group.getId())); DBObject mostRecent = null; for (DBObject rec : this.hourlyCollection.find(find)) { if (mostRecent == null) { mostRecent = rec; } else if (((Date) mostRecent.get("date")).getTime() < ((Date) rec.get("date")).getTime()) { mostRecent = rec; } } try { XMLGregorianCalendar last = DateConvert.convertDate(((Date) mostRecent.get("date"))); data = getHourlyEnergyData(group, last, now); objects = buildDBFromInterpolatedValues(data); logger.info(IdHelper.niceifyTowerId(group.getId()) + ": " + objects.size() + " records added"); for (BasicDBObject doc : objects) { this.hourlyCollection.insert(doc); } // do we need to create prediction? for (InterpolatedValue value : data.getInterpolatedValues()) { XMLGregorianCalendar time = DateConvert.convertDate(value.getStart()); logger.info("prediction for " + time + " made"); InterpolatedValueList histData = getHistoricalHourlyEnergyData(group, time, 7); BasicDBObject histObj = buildHourlyHistoryDBObject(histData); this.predictedHourlyCollection.insert(histObj); } } catch (DatatypeConfigurationException e) { e.printStackTrace(); } } } /** * Removes all the hourly energy data from the database. * * @return The number of entries removed. */ private Integer clearHourlyEnergy() { Integer integer = null; for (SensorGroup group : towerList) { logger.info("clearing hourly data for " + IdHelper.niceifyTowerId(group.getId())); BasicDBObject remove = new BasicDBObject("tower", IdHelper.niceifyTowerId(group.getId())); WriteResult result = this.hourlyCollection.remove(remove); if (integer == null) { integer = new Integer(0); } integer += result.getN(); this.predictedHourlyCollection.remove(remove); } return integer; } /** * Updates the hourly power history for each tower. Should be run once an hour. */ public void updatePowerHistory() { for (SensorGroup tower : towerList) { logger.info("update power history for " + IdHelper.niceifyTowerId(tower.getId())); DescriptiveStats values = client.getDescriptiveStats(powerDepository, tower, new Date(), false, 5, true); powerHistory.put(tower, values); } } /** * Updates the Hale Aloha Sensor Status. * * @return The number statues sent to the dashboard. */ public Integer updateSensorStatus() { Integer ret = 0; for (SensorGroup group : towerList) { logger.info("update sensor status for " + IdHelper.niceifyTowerId(group.getId())); SensorStatusList statusList = client.getSensorStatuses(powerDepository, group); ArrayList<BasicDBObject> objects = buildDBFromSensorStatusList(statusList); ret += objects.size(); for (BasicDBObject doc : objects) { statusCollection.insert(doc); } } return ret; } private XMLGregorianCalendar beginningOfHour(XMLGregorianCalendar when) { XMLGregorianCalendar begin = Tstamp.makeTimestamp(when.toGregorianCalendar().getTimeInMillis()); begin.setMinute(0); begin.setSecond(0); begin.setMillisecond(0); return begin; } /** * Builds BasicDBObjects representing the InterpolatedValues. * * @param list the list of InterpolatedValues. * @return the list of BasicDBObjects. */ private ArrayList<BasicDBObject> buildDBFromInterpolatedValues(InterpolatedValueList list) { ArrayList<BasicDBObject> ret = new ArrayList<BasicDBObject>(); assert (list != null); for (InterpolatedValue value : list.getInterpolatedValues()) { ret.add(buildIvDbObject(value)); } return ret; } /** * Builds BasicDBObjects representing the SensorStatuses. * * @param list the list of SensorStatuses. * @return the list of BasicDBObjects. */ private ArrayList<BasicDBObject> buildDBFromSensorStatusList(SensorStatusList list) { ArrayList<BasicDBObject> ret = new ArrayList<BasicDBObject>(); assert (list != null); for (org.wattdepot.common.domainmodel.SensorStatus status : list.getStatuses()) { ret.add(buildStatusDbObject(status)); } return ret; } /** * Builds a BasicDBObject from the SensorStatus. * * @param status the SensorStatus. * @return the BasicDBObject. */ private BasicDBObject buildStatusDbObject(org.wattdepot.common.domainmodel.SensorStatus status) { BasicDBObject ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(status.getSensorId())) .append("status", status.getStatus().getLabel()) .append("sensorId", status.getSensorId()) .append("date", status.getTimestamp().toXMLFormat()) .append("createdAt", new Date()); return ret; } /** * Builds a BasicDBObject from the InterpolatedValue. * * @param value the InterpolatedValue. * @return the BasicDBObject. */ private BasicDBObject buildIvDbObject(InterpolatedValue value) { BasicDBObject ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(value.getSensorId())) .append("value", value.getValue()) .append("date", value.getEnd()) .append("createdAt", new Date()); return ret; } private BasicDBObject buildDailyHistoryDBObject(InterpolatedValueList interpolatedValueList) { if (interpolatedValueList.getInterpolatedValues().size() > 0) { SimpleDateFormat format = new SimpleDateFormat("MM/dd"); InterpolatedValue first = interpolatedValueList.getInterpolatedValues().get(0); XMLGregorianCalendar time = Tstamp.makeTimestamp(first.getStart().getTime()); time = Tstamp.incrementDays(time, 7); BasicDBObject ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(first.getSensorId())) .append("date", first.getStart()) .append("label", format.format(DateConvert.convertXMLCal(time))) .append("createdAt", new Date()); BasicDBList values = new BasicDBList(); for (InterpolatedValue v : interpolatedValueList.getInterpolatedValues()) { values.add(v.getValue() / 1000.0); // put into kW instead of W. } ret.append("values", values); return ret; } return null; } private BasicDBObject buildHourlyHistoryDBObject(InterpolatedValueList interpolatedValueList) { if (interpolatedValueList.getInterpolatedValues().size() > 0) { SimpleDateFormat format = new SimpleDateFormat("hha"); InterpolatedValue first = interpolatedValueList.getInterpolatedValues().get(0); XMLGregorianCalendar time = Tstamp.makeTimestamp(first.getStart().getTime()); time = Tstamp.incrementDays(time, 7); BasicDBObject ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(first.getSensorId())) .append("date", first.getStart()) .append("label", format.format(DateConvert.convertXMLCal(time))) .append("createdAt", new Date()); BasicDBList values = new BasicDBList(); for (InterpolatedValue v : interpolatedValueList.getInterpolatedValues()) { values.add(v.getValue() / 1000.0); // put into kW instead of W. } ret.append("values", values); return ret; } return null; } private BasicDBObject buildPowerDBObject(InterpolatedValue value) { SensorGroup group = null; for (SensorGroup g : towerList) { if (g.getId().equals(value.getSensorId())) { group = g; } } Double currentPower = value.getValue(); BasicDBObject ret = null; DescriptiveStats val = powerHistory.get(group); if (val != null) { Double min = val.getMinimum(); if (min.isNaN()) { min = value.getValue() / 2; } if (min > currentPower) { min = currentPower - 0.1 * currentPower; } Double max = val.getMaximum(); if (max.isNaN()) { max = value.getValue() * 1.5; } if (max < currentPower) { max = currentPower + 0.1 * currentPower; } Double ave = val.getAverage(); if (ave.isNaN()) { ave = currentPower; } ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(value.getSensorId())) .append("value", currentPower) .append("minimum", min) .append("maximum", max) .append("average", ave) .append("meters", value.getDefinedSensors().size()) .append("reporting", value.getReportingSensors().size()) .append("timestamp", value.getEnd()) .append("createdAt", new Date()); } else { currentPower = value.getValue(); Double min = currentPower - 0.5 * currentPower; Double max = currentPower + 0.5 * currentPower; ret = new BasicDBObject("tower", IdHelper.niceifyTowerId(value.getSensorId())) .append("value", currentPower) .append("minimum", min) .append("maximum", max) .append("average", 7500.0) .append("meters", value.getDefinedSensors().size()) .append("reporting", value.getReportingSensors().size()) .append("timestamp", value.getEnd()) .append("createdAt", new Date()); } return ret; } private XMLGregorianCalendar endingOfHour(XMLGregorianCalendar when) { XMLGregorianCalendar end = Tstamp.incrementHours(when, 1); end.setMinute(0); end.setSecond(0); end.setMillisecond(0); return end; } /** * Gets the daily energy data. * * @param group the group to get the data for. * @param start The beginning datetime. * @param end The ending datetime. * @return An InterpolatedValueList of the daily energy data. */ private InterpolatedValueList getDailyEnergyData(SensorGroup group, XMLGregorianCalendar start, XMLGregorianCalendar end) { InterpolatedValueList dailyData = this.client.getDailyValues(this.energyDepository, group, DateConvert.convertXMLCal(start), DateConvert.convertXMLCal(end), false); return dailyData; } /** * Gets the hourly energy data. * * @param group the group to get the data for. * @param start The beginning datetime. * @param end The ending datetime. * @return An InterpolatedValueList of the hourly energy data. */ private InterpolatedValueList getHourlyEnergyData(SensorGroup group, XMLGregorianCalendar start, XMLGregorianCalendar end) { InterpolatedValueList hourlyData = this.client.getHourlyValues(this.energyDepository, group, DateConvert.convertXMLCal(start), DateConvert.convertXMLCal(end), false); return hourlyData; } /** * Gets the hourly historical data. * * @param group the group to get the data for. * @param time the start time for the historical data. Historical data is weekly one week before. * @param numSamples the number of weeks to go back. * @return An InterpolatedValueList of the historical data. */ private InterpolatedValueList getHistoricalHourlyEnergyData(SensorGroup group, XMLGregorianCalendar time, Integer numSamples) { InterpolatedValueList hourlyData = this.client.getHistoricalValues(this.energyDepository, group, DateConvert.convertXMLCal(time), false, numSamples, false); return hourlyData; } /** * Gets the daily historical data. * * @param group the group to get the data for. * @param time the start time for the historical data. Historical data is weekly one week before. * @param numSamples the number of weeks to go back. * @return An InterpolatedValueList of the historical data. */ private InterpolatedValueList getHistoricalDailyEnergyData(SensorGroup group, XMLGregorianCalendar time, Integer numSamples) { InterpolatedValueList dailyData = this.client.getHistoricalValues(this.energyDepository, group, DateConvert.convertXMLCal(time), true, numSamples, false); return dailyData; } }
package pokeraidbot.commands; import com.jagrosh.jdautilities.commandclient.CommandEvent; import com.jagrosh.jdautilities.commandclient.CommandListener; import pokeraidbot.domain.config.LocaleService; import pokeraidbot.infrastructure.jpa.config.Config; import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository; public class DonateCommand extends ConfigAwareCommand { private static final String link = "https: public DonateCommand(LocaleService localeService, ServerConfigRepository serverConfigRepository, CommandListener commandListener) { super(serverConfigRepository, commandListener, localeService); this.name = "donate"; this.help = localeService.getMessageFor(LocaleService.DONATE, LocaleService.DEFAULT); } @Override protected void executeWithConfig(CommandEvent commandEvent, Config config) { replyBasedOnConfig(config, commandEvent, link); } }
package org.cqframework.cql.cql2elm; import org.cqframework.cql.cql2elm.model.*; import org.cqframework.cql.cql2elm.model.invocation.AggregateExpressionInvocation; import org.cqframework.cql.cql2elm.model.invocation.BinaryExpressionInvocation; import org.cqframework.cql.cql2elm.model.invocation.FunctionRefInvocation; import org.cqframework.cql.cql2elm.model.invocation.UnaryExpressionInvocation; import org.hl7.cql.model.*; import org.hl7.cql_annotations.r1.CqlToElmError; import org.hl7.cql_annotations.r1.ErrorType; import org.hl7.elm.r1.*; import org.hl7.elm_modelinfo.r1.ModelInfo; import javax.xml.namespace.QName; import java.util.*; import java.util.List; public class LibraryBuilder { public LibraryBuilder(ModelManager modelManager, LibraryManager libraryManager) { if (modelManager == null) { throw new IllegalArgumentException("modelManager is null"); } if (libraryManager == null) { throw new IllegalArgumentException("libraryManager is null"); } this.modelManager = modelManager; this.libraryManager = libraryManager; this.library = of.createLibrary() .withSchemaIdentifier(of.createVersionedIdentifier() .withId("urn:hl7-org:elm") // TODO: Pull this from the ELM library namespace .withVersion("r1")); translatedLibrary = new TranslatedLibrary(); translatedLibrary.setLibrary(library); } private final java.util.List<CqlTranslatorException> errors = new ArrayList<>(); public List<CqlTranslatorException> getErrors() { return errors; } private final Map<String, Model> models = new HashMap<>(); private final Map<String, TranslatedLibrary> libraries = new HashMap<>(); private final SystemFunctionResolver systemFunctionResolver = new SystemFunctionResolver(this); private final Stack<String> expressionContext = new Stack<>(); private final Stack<String> expressionDefinitions = new Stack<>(); private final Stack<Expression> targets = new Stack<>(); private FunctionDef currentFunctionDef = null; private ModelManager modelManager = null; private Model defaultModel = null; private LibraryManager libraryManager = null; private Library library = null; public Library getLibrary() { return library; } private TranslatedLibrary translatedLibrary = null; public TranslatedLibrary getTranslatedLibrary() { return translatedLibrary; } private final ConversionMap conversionMap = new ConversionMap(); public ConversionMap getConversionMap() { return conversionMap; } private final ObjectFactory of = new ObjectFactory(); private final org.hl7.cql_annotations.r1.ObjectFactory af = new org.hl7.cql_annotations.r1.ObjectFactory(); private final Stack<QueryContext> queries = new Stack<>(); private Model loadModel(VersionedIdentifier modelIdentifier) { Model model = modelManager.resolveModel(modelIdentifier); loadConversionMap(model); return model; } public Model getDefaultModel() { return defaultModel; } private void setDefaultModel(Model model) { // The default model is the first model that is not System if (defaultModel == null && !model.getModelInfo().getName().equals("System")) { defaultModel = model; } } public Model getModel(VersionedIdentifier modelIdentifier) { Model model = models.get(modelIdentifier.getId()); if (model == null) { model = loadModel(modelIdentifier); setDefaultModel(model); models.put(modelIdentifier.getId(), model); // Add the model using def to the output buildUsingDef(modelIdentifier, model); } if (modelIdentifier.getVersion() != null && !modelIdentifier.getVersion().equals(model.getModelInfo().getVersion())) { throw new IllegalArgumentException(String.format("Could not load model information for model %s, version %s because version %s is already loaded.", modelIdentifier.getId(), modelIdentifier.getVersion(), model.getModelInfo().getVersion())); } return model; } private void loadConversionMap(Model model) { for (Conversion conversion : model.getConversions()) { conversionMap.add(conversion); } } private UsingDef buildUsingDef(VersionedIdentifier modelIdentifier, Model model) { UsingDef usingDef = of.createUsingDef() .withLocalIdentifier(modelIdentifier.getId()) .withVersion(modelIdentifier.getVersion()) .withUri(model.getModelInfo().getUrl()); // TODO: Needs to write xmlns and schemalocation to the resulting ELM XML document... addUsing(usingDef); return usingDef; } public boolean hasUsings() { for (Model model : models.values()) { if (!model.getModelInfo().getName().equals("System")) { return true; } } return false; } private void addUsing(UsingDef usingDef) { if (library.getUsings() == null) { library.setUsings(of.createLibraryUsings()); } library.getUsings().getDef().add(usingDef); translatedLibrary.add(usingDef); } public ClassType resolveLabel(String modelName, String label) { ClassType result = null; if (modelName == null || modelName.equals("")) { for (Model model : models.values()) { ClassType modelResult = model.resolveLabel(label); if (modelResult != null) { if (result != null) { throw new IllegalArgumentException(String.format("Label %s is ambiguous between %s and %s.", label, result.getName(), modelResult.getName())); } result = modelResult; } } } else { result = getModel(modelName).resolveLabel(label); } return result; } public DataType resolveTypeName(String typeName) { return resolveTypeName(null, typeName); } public DataType resolveTypeName(String modelName, String typeName) { // Attempt to resolve as a label first DataType result = resolveLabel(modelName, typeName); if (result == null) { if (modelName == null || modelName.equals("")) { // Attempt to resolve in the default model if one is available if (defaultModel != null) { DataType modelResult = defaultModel.resolveTypeName(typeName); if (modelResult != null) { return modelResult; } } // Otherwise, resolve across all models and throw for ambiguous resolution for (Model model : models.values()) { DataType modelResult = model.resolveTypeName(typeName); if (modelResult != null) { if (result != null) { throw new IllegalArgumentException(String.format("Type name %s is ambiguous between %s and %s.", typeName, ((NamedType) result).getName(), ((NamedType) modelResult).getName())); } result = modelResult; } } } else { result = getModel(modelName).resolveTypeName(typeName); } } return result; } public UsingDef resolveUsingRef(String modelName) { return translatedLibrary.resolveUsingRef(modelName); } public SystemModel getSystemModel() { // TODO: Support loading different versions of the system library return (SystemModel)getModel(new VersionedIdentifier().withId("System")); } public Model getModel(String modelName) { UsingDef usingDef = resolveUsingRef(modelName); if (usingDef == null) { throw new IllegalArgumentException(String.format("Could not resolve model name %s", modelName)); } return getModel(new VersionedIdentifier().withId(usingDef.getLocalIdentifier()).withVersion(usingDef.getVersion())); } private void loadSystemLibrary() { TranslatedLibrary systemLibrary = SystemLibraryHelper.load(getSystemModel()); libraries.put(systemLibrary.getIdentifier().getId(), systemLibrary); loadConversionMap(systemLibrary); } private void loadConversionMap(TranslatedLibrary library) { for (Conversion conversion : library.getConversions()) { conversionMap.add(conversion); } } public TranslatedLibrary getSystemLibrary() { return resolveLibrary("System"); } public TranslatedLibrary resolveLibrary(String identifier) { TranslatedLibrary result = libraries.get(identifier); if (result == null) { throw new IllegalArgumentException(String.format("Could not resolve library name %s.", identifier)); } return result; } /** * Record any errors while parsing in both the list of errors but also in the library * itself so they can be processed easily by a remote client * @param e the exception to record */ public void recordParsingException(CqlTranslatorException e) { errors.add(e); CqlToElmError err = af.createCqlToElmError(); err.setMessage(e.getMessage()); err.setErrorType(ErrorType.SYNTAX); if (e.getLocator() != null) { err.setStartLine(e.getLocator().getStartLine()); err.setEndLine(e.getLocator().getEndLine()); err.setStartChar(e.getLocator().getStartChar()); err.setEndChar(e.getLocator().getEndChar()); } if (e.getCause() != null && e.getCause() instanceof CqlTranslatorIncludeException) { CqlTranslatorIncludeException incEx = (CqlTranslatorIncludeException)e.getCause(); err.setTargetIncludeLibraryId(incEx.getLibraryId()); err.setTargetIncludeLibraryVersionId(incEx.getVersionId()); err.setErrorType(ErrorType.INCLUDE); } library.getAnnotation().add(err); } private String getLibraryName() { String libraryName = library.getIdentifier().getId(); if (libraryName == null) { libraryName = "Anonymous"; } return libraryName; } public void beginTranslation() { loadSystemLibrary(); libraryManager.beginTranslation(getLibraryName()); } public VersionedIdentifier getLibraryIdentifier() { return library.getIdentifier(); } public void setLibraryIdentifier(VersionedIdentifier vid) { library.setIdentifier(vid); translatedLibrary.setIdentifier(vid); } public void endTranslation() { libraryManager.endTranslation(getLibraryName()); } public void addInclude(IncludeDef includeDef) { if (library.getIdentifier() == null || library.getIdentifier().getId() == null) { throw new IllegalArgumentException("Unnamed libraries cannot reference other libraries."); } if (library.getIncludes() == null) { library.setIncludes(of.createLibraryIncludes()); } library.getIncludes().getDef().add(includeDef); translatedLibrary.add(includeDef); VersionedIdentifier libraryIdentifier = new VersionedIdentifier() .withId(includeDef.getPath()) .withVersion(includeDef.getVersion()); TranslatedLibrary referencedLibrary = libraryManager.resolveLibrary(libraryIdentifier, errors); libraries.put(includeDef.getLocalIdentifier(), referencedLibrary); loadConversionMap(referencedLibrary); } public void addParameter(ParameterDef paramDef) { if (library.getParameters() == null) { library.setParameters(of.createLibraryParameters()); } library.getParameters().getDef().add(paramDef); translatedLibrary.add(paramDef); } public void addCodeSystem(CodeSystemDef cs) { if (library.getCodeSystems() == null) { library.setCodeSystems(of.createLibraryCodeSystems()); } library.getCodeSystems().getDef().add(cs); translatedLibrary.add(cs); } public void addValueSet(ValueSetDef vs) { if (library.getValueSets() == null) { library.setValueSets(of.createLibraryValueSets()); } library.getValueSets().getDef().add(vs); translatedLibrary.add(vs); } public void addCode(CodeDef cd) { if (library.getCodes() == null) { library.setCodes(of.createLibraryCodes()); } library.getCodes().getDef().add(cd); translatedLibrary.add(cd); } public void addConcept(ConceptDef cd) { if (library.getConcepts() == null) { library.setConcepts(of.createLibraryConcepts()); } library.getConcepts().getDef().add(cd); translatedLibrary.add(cd); } public void addExpression(ExpressionDef expDef) { if (library.getStatements() == null) { library.setStatements(of.createLibraryStatements()); } library.getStatements().getDef().add(expDef); translatedLibrary.add(expDef); } public Element resolve(String identifier) { return translatedLibrary.resolve(identifier); } public IncludeDef resolveIncludeRef(String identifier) { return translatedLibrary.resolveIncludeRef(identifier); } public CodeSystemDef resolveCodeSystemRef(String identifier) { return translatedLibrary.resolveCodeSystemRef(identifier); } public ValueSetDef resolveValueSetRef(String identifier) { return translatedLibrary.resolveValueSetRef(identifier); } public CodeDef resolveCodeRef(String identifier) { return translatedLibrary.resolveCodeRef(identifier); } public ConceptDef resolveConceptRef(String identifier) { return translatedLibrary.resolveConceptRef(identifier); } public ParameterDef resolveParameterRef(String identifier) { return translatedLibrary.resolveParameterRef(identifier); } public ExpressionDef resolveExpressionRef(String identifier) { return translatedLibrary.resolveExpressionRef(identifier); } public Conversion findConversion(DataType fromType, DataType toType, boolean implicit) { return conversionMap.findConversion(fromType, toType, implicit, translatedLibrary.getOperatorMap()); } public Expression resolveUnaryCall(String libraryName, String operatorName, UnaryExpression expression) { return resolveCall(libraryName, operatorName, new UnaryExpressionInvocation(expression)); } public Expression resolveBinaryCall(String libraryName, String operatorName, BinaryExpression expression) { return resolveCall(libraryName, operatorName, new BinaryExpressionInvocation(expression)); } public Expression resolveAggregateCall(String libraryName, String operatorName, AggregateExpression expression) { return resolveCall(libraryName, operatorName, new AggregateExpressionInvocation(expression)); } public Expression resolveCall(String libraryName, String operatorName, Invocation invocation) { Iterable<Expression> operands = invocation.getOperands(); List<DataType> dataTypes = new ArrayList<>(); for (Expression operand : operands) { if (operand.getResultType() == null) { throw new IllegalArgumentException(String.format("Could not determine signature for invocation of operator %s%s.", libraryName == null ? "" : libraryName + ".", operatorName)); } dataTypes.add(operand.getResultType()); } CallContext callContext = new CallContext(libraryName, operatorName, dataTypes.toArray(new DataType[dataTypes.size()])); OperatorResolution resolution = resolveCall(callContext); checkOperator(callContext, resolution); if (resolution.hasConversions()) { List<Expression> convertedOperands = new ArrayList<>(); Iterator<Expression> operandIterator = operands.iterator(); Iterator<Conversion> conversionIterator = resolution.getConversions().iterator(); while (operandIterator.hasNext()) { Expression operand = operandIterator.next(); Conversion conversion = conversionIterator.next(); if (conversion != null) { convertedOperands.add(convertExpression(operand, conversion)); } else { convertedOperands.add(operand); } } invocation.setOperands(convertedOperands); } invocation.setResultType(resolution.getOperator().getResultType()); return invocation.getExpression(); } public OperatorResolution resolveCall(CallContext callContext) { OperatorResolution result = null; if (callContext.getLibraryName() == null || callContext.getLibraryName().equals("")) { result = translatedLibrary.resolveCall(callContext, conversionMap); if (result == null) { result = getSystemLibrary().resolveCall(callContext, conversionMap); if (result != null) { checkAccessLevel(result.getOperator().getLibraryName(), result.getOperator().getName(), result.getOperator().getAccessLevel()); } } } else { result = resolveLibrary(callContext.getLibraryName()).resolveCall(callContext, conversionMap); } return result; } public void checkOperator(CallContext callContext, OperatorResolution resolution) { if (resolution == null) { throw new IllegalArgumentException(String.format("Could not resolve call to operator %s with signature %s.", callContext.getOperatorName(), callContext.getSignature())); } } public void checkAccessLevel(String libraryName, String objectName, AccessModifier accessModifier) { if (accessModifier == AccessModifier.PRIVATE) { throw new IllegalArgumentException(String.format("Object %s in library %s is marked private and cannot be referenced from another library.", objectName, libraryName)); } } public Expression resolveFunction(String libraryName, String functionName, Iterable<Expression> paramList) { FunctionRef fun = of.createFunctionRef() .withLibraryName(libraryName) .withName(functionName); for (Expression param : paramList) { fun.getOperand().add(param); } Expression systemFunction = systemFunctionResolver.resolveSystemFunction(fun); if (systemFunction != null) { return systemFunction; } resolveCall(fun.getLibraryName(), fun.getName(), new FunctionRefInvocation(fun)); return fun; } public Expression convertExpression(Expression expression, DataType targetType) { Conversion conversion = findConversion(expression.getResultType(), targetType, true); if (conversion != null) { return convertExpression(expression, conversion); } DataTypes.verifyType(expression.getResultType(), targetType); return expression; } private Expression convertListExpression(Expression expression, Conversion conversion) { ListType fromType = (ListType)conversion.getFromType(); ListType toType = (ListType)conversion.getToType(); Query query = (Query)of.createQuery() .withSource((AliasedQuerySource) of.createAliasedQuerySource() .withAlias("X") .withExpression(expression) .withResultType(fromType)) .withReturn((ReturnClause) of.createReturnClause() .withDistinct(false) .withExpression(convertExpression((AliasRef) of.createAliasRef() .withName("X") .withResultType(fromType.getElementType()), conversion.getConversion())) .withResultType(toType)) .withResultType(toType); return query; } private Expression demoteListExpression(Expression expression, Conversion conversion) { ListType fromType = (ListType)conversion.getFromType(); DataType toType = conversion.getToType(); SingletonFrom singletonFrom = of.createSingletonFrom().withOperand(expression); singletonFrom.setResultType(fromType.getElementType()); resolveUnaryCall("System", "SingletonFrom", singletonFrom); if (conversion.getConversion() != null) { return convertExpression(singletonFrom, conversion.getConversion()); } else { return singletonFrom; } } private Expression promoteListExpression(Expression expression, Conversion conversion) { if (conversion.getConversion() != null) { expression = convertExpression(expression, conversion.getConversion()); } org.hl7.elm.r1.List list = of.createList(); list.getElement().add(expression); list.setResultType(new ListType(expression.getResultType())); return list; } private Expression convertIntervalExpression(Expression expression, Conversion conversion) { IntervalType fromType = (IntervalType)conversion.getFromType(); IntervalType toType = (IntervalType)conversion.getToType(); Interval interval = (Interval)of.createInterval() .withLow(convertExpression((Property)of.createProperty() .withSource(expression) .withPath("low") .withResultType(fromType.getPointType()), conversion.getConversion())) .withLowClosedExpression((Property) of.createProperty() .withSource(expression) .withPath("lowClosed") .withResultType(resolveTypeName("System", "Boolean"))) .withHigh(convertExpression((Property) of.createProperty() .withSource(expression) .withPath("high") .withResultType(fromType.getPointType()), conversion.getConversion())) .withHighClosedExpression((Property) of.createProperty() .withSource(expression) .withPath("highClosed") .withResultType(resolveTypeName("System", "Boolean"))) .withResultType(toType); return interval; } public Expression convertExpression(Expression expression, Conversion conversion) { if (conversion.isCast() && (conversion.getFromType().isSuperTypeOf(conversion.getToType()) || conversion.getFromType().isCompatibleWith(conversion.getToType()))) { As castedOperand = (As)of.createAs() .withOperand(expression) .withResultType(conversion.getToType()); castedOperand.setAsTypeSpecifier(dataTypeToTypeSpecifier(castedOperand.getResultType())); if (castedOperand.getResultType() instanceof NamedType) { castedOperand.setAsType(dataTypeToQName(castedOperand.getResultType())); } return castedOperand; } else if (conversion.isCast() && conversion.getConversion() != null && (conversion.getFromType().isSuperTypeOf(conversion.getConversion().getFromType()) || conversion.getFromType().isCompatibleWith(conversion.getConversion().getFromType()))) { As castedOperand = (As)of.createAs() .withOperand(expression) .withResultType(conversion.getConversion().getFromType()); castedOperand.setAsTypeSpecifier(dataTypeToTypeSpecifier(castedOperand.getResultType())); if (castedOperand.getResultType() instanceof NamedType) { castedOperand.setAsType(dataTypeToQName(castedOperand.getResultType())); } return convertExpression(castedOperand, conversion.getConversion()); } else if (conversion.isListConversion()) { return convertListExpression(expression, conversion); } else if (conversion.isListDemotion()) { return demoteListExpression(expression, conversion); } else if (conversion.isListPromotion()) { return promoteListExpression(expression, conversion); } else if (conversion.isIntervalConversion()) { return convertIntervalExpression(expression, conversion); } else if (conversion.getOperator() != null) { FunctionRef functionRef = (FunctionRef)of.createFunctionRef() .withLibraryName(conversion.getOperator().getLibraryName()) .withName(conversion.getOperator().getName()) .withOperand(expression); Expression systemFunction = systemFunctionResolver.resolveSystemFunction(functionRef); if (systemFunction != null) { return systemFunction; } resolveCall(functionRef.getLibraryName(), functionRef.getName(), new FunctionRefInvocation(functionRef)); return functionRef; } else { if (conversion.getToType().equals(resolveTypeName("System", "Boolean"))) { return (Expression)of.createToBoolean().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "Integer"))) { return (Expression)of.createToInteger().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "Decimal"))) { return (Expression)of.createToDecimal().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "String"))) { return (Expression)of.createToString().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "DateTime"))) { return (Expression)of.createToDateTime().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "Time"))) { return (Expression)of.createToTime().withOperand(expression).withResultType(conversion.getToType()); } else if (conversion.getToType().equals(resolveTypeName("System", "Quantity"))) { return (Expression)of.createToQuantity().withOperand(expression).withResultType(conversion.getToType()); } else { Convert convertedOperand = (Convert)of.createConvert() .withOperand(expression) .withResultType(conversion.getToType()); if (convertedOperand.getResultType() instanceof NamedType) { convertedOperand.setToType(dataTypeToQName(convertedOperand.getResultType())); } else { convertedOperand.setToTypeSpecifier(dataTypeToTypeSpecifier(convertedOperand.getResultType())); } return convertedOperand; } } } public void verifyType(DataType actualType, DataType expectedType) { if (expectedType.isSuperTypeOf(actualType) || actualType.isCompatibleWith(expectedType)) { return; } Conversion conversion = findConversion(actualType, expectedType, true); if (conversion != null) { return; } DataTypes.verifyType(actualType, expectedType); } public DataType ensureCompatibleTypes(DataType first, DataType second) { if (first.equals(DataType.ANY)) { return second; } if (second.equals(DataType.ANY)) { return first; } if (first.isSuperTypeOf(second) || second.isCompatibleWith(first)) { return first; } if (second.isSuperTypeOf(first) || first.isCompatibleWith(second)) { return second; } Conversion conversion = findConversion(second, first, true); if (conversion != null) { return first; } conversion = findConversion(first, second, true); if (conversion != null) { return second; } DataTypes.verifyType(second, first); return first; } public Expression ensureCompatible(Expression expression, DataType targetType) { if (!targetType.isSuperTypeOf(expression.getResultType())) { return convertExpression(expression, targetType); } return expression; } public QName dataTypeToQName(DataType type) { if (type instanceof NamedType) { NamedType namedType = (NamedType)type; ModelInfo modelInfo = getModel(namedType.getNamespace()).getModelInfo(); return new QName(modelInfo.getUrl(), namedType.getSimpleName()); } throw new IllegalArgumentException("A named type is required in this context."); } public TypeSpecifier dataTypeToTypeSpecifier(DataType type) { // Convert the given type into an ELM TypeSpecifier representation. if (type instanceof NamedType) { return (TypeSpecifier)of.createNamedTypeSpecifier().withName(dataTypeToQName(type)).withResultType(type); } else if (type instanceof ListType) { return listTypeToTypeSpecifier((ListType)type); } else if (type instanceof IntervalType) { return intervalTypeToTypeSpecifier((IntervalType)type); } else if (type instanceof TupleType) { return tupleTypeToTypeSpecifier((TupleType)type); } else if (type instanceof ChoiceType) { return choiceTypeToTypeSpecifier((ChoiceType)type); } else { throw new IllegalArgumentException(String.format("Could not convert type %s to a type specifier.", type)); } } private TypeSpecifier listTypeToTypeSpecifier(ListType type) { return (TypeSpecifier)of.createListTypeSpecifier() .withElementType(dataTypeToTypeSpecifier(type.getElementType())) .withResultType(type); } private TypeSpecifier intervalTypeToTypeSpecifier(IntervalType type) { return (TypeSpecifier)of.createIntervalTypeSpecifier() .withPointType(dataTypeToTypeSpecifier(type.getPointType())) .withResultType(type); } private TypeSpecifier tupleTypeToTypeSpecifier(TupleType type) { return (TypeSpecifier)of.createTupleTypeSpecifier() .withElement(tupleTypeElementsToTupleElementDefinitions(type.getElements())) .withResultType(type); } private TupleElementDefinition[] tupleTypeElementsToTupleElementDefinitions(Iterable<TupleTypeElement> elements) { List<TupleElementDefinition> definitions = new ArrayList<>(); for (TupleTypeElement element : elements) { definitions.add(of.createTupleElementDefinition() .withName(element.getName()) .withType(dataTypeToTypeSpecifier(element.getType()))); } return definitions.toArray(new TupleElementDefinition[definitions.size()]); } private TypeSpecifier choiceTypeToTypeSpecifier(ChoiceType type) { return (TypeSpecifier)of.createChoiceTypeSpecifier() .withType(choiceTypeTypesToTypeSpecifiers(type)) .withResultType(type); } private TypeSpecifier[] choiceTypeTypesToTypeSpecifiers(ChoiceType choiceType) { List<TypeSpecifier> specifiers = new ArrayList<>(); for (DataType type : choiceType.getTypes()) { specifiers.add(dataTypeToTypeSpecifier(type)); } return specifiers.toArray(new TypeSpecifier[specifiers.size()]); } public DataType resolvePath(DataType sourceType, String path) { // TODO: This is using a naive implementation for now... needs full path support (but not full FluentPath support...) String[] identifiers = path.split("\\."); for (int i = 0; i < identifiers.length; i++) { sourceType = resolveProperty(sourceType, identifiers[i]); } return sourceType; } public DataType resolveProperty(DataType sourceType, String identifier) { return resolveProperty(sourceType, identifier, true); } // TODO: Support case-insensitive models public DataType resolveProperty(DataType sourceType, String identifier, boolean mustResolve) { DataType currentType = sourceType; while (currentType != null) { if (currentType instanceof ClassType) { ClassType classType = (ClassType)currentType; for (ClassTypeElement e : classType.getElements()) { if (e.getName().equals(identifier)) { if (e.isProhibited()) { throw new IllegalArgumentException(String.format("Element %s cannot be referenced because it is marked prohibited in type %s.", e.getName(), ((ClassType) currentType).getName())); } return e.getType(); } } } else if (currentType instanceof TupleType) { TupleType tupleType = (TupleType)currentType; for (TupleTypeElement e : tupleType.getElements()) { if (e.getName().equals(identifier)) { return e.getType(); } } } else if (currentType instanceof IntervalType) { IntervalType intervalType = (IntervalType)currentType; switch (identifier) { case "low": case "high": return intervalType.getPointType(); case "lowClosed": case "highClosed": return resolveTypeName("System", "Boolean"); default: throw new IllegalArgumentException(String.format("Invalid interval property name %s.", identifier)); } } else if (currentType instanceof ChoiceType) { ChoiceType choiceType = (ChoiceType)currentType; // TODO: Issue a warning if the property does not resolve against every type in the choice // Resolve the property against each type in the choice Set<DataType> resultTypes = new HashSet<>(); for (DataType choice : choiceType.getTypes()) { DataType resultType = resolveProperty(choice, identifier, false); if (resultType != null) { resultTypes.add(resultType); } } // The result type is a choice of all the resolved types if (resultTypes.size() > 1) { return new ChoiceType(resultTypes); } if (resultTypes.size() == 1) { for (DataType resultType : resultTypes) { return resultType; } } } if (currentType.getBaseType() != null) { currentType = currentType.getBaseType(); } else { break; } } if (mustResolve) { throw new IllegalArgumentException(String.format("Member %s not found for type %s.", identifier, sourceType)); } return null; } public Expression resolveIdentifier(String identifier, boolean mustResolve) { // An Identifier will always be: // 1: The name of an alias // 2: The name of a query define clause // 3: The name of an expression // 4: The name of a parameter // 5: The name of a valueset // 6: The name of a codesystem // 7: The name of a code // 8: The name of a concept // 9: The name of a library // 10: An unresolved identifier error is thrown // In the sort clause of a plural query, names may be resolved based on the result type of the query IdentifierRef resultElement = resolveQueryResultElement(identifier); if (resultElement != null) { return resultElement; } // In the case of a $this alias, names may be resolved as implicit property references Expression thisElement = resolveQueryThisElement(identifier); if (thisElement != null) { return thisElement; } AliasedQuerySource alias = resolveAlias(identifier); if (alias != null) { AliasRef result = of.createAliasRef().withName(identifier); if (alias.getResultType() instanceof ListType) { result.setResultType(((ListType)alias.getResultType()).getElementType()); } else { result.setResultType(alias.getResultType()); } return result; } LetClause let = resolveQueryLet(identifier); if (let != null) { QueryLetRef result = of.createQueryLetRef().withName(identifier); result.setResultType(let.getResultType()); return result; } OperandRef operandRef = resolveOperandRef(identifier); if (operandRef != null) { return operandRef; } Element element = resolve(identifier); if (element instanceof ExpressionDef) { ExpressionRef expressionRef = of.createExpressionRef().withName(((ExpressionDef) element).getName()); expressionRef.setResultType(getExpressionDefResultType((ExpressionDef)element)); return expressionRef; } if (element instanceof ParameterDef) { ParameterRef parameterRef = of.createParameterRef().withName(((ParameterDef) element).getName()); parameterRef.setResultType(element.getResultType()); return parameterRef; } if (element instanceof ValueSetDef) { ValueSetRef valuesetRef = of.createValueSetRef().withName(((ValueSetDef) element).getName()); valuesetRef.setResultType(element.getResultType()); return valuesetRef; } if (element instanceof CodeSystemDef) { CodeSystemRef codesystemRef = of.createCodeSystemRef().withName(((CodeSystemDef) element).getName()); codesystemRef.setResultType(element.getResultType()); return codesystemRef; } if (element instanceof CodeDef) { CodeRef codeRef = of.createCodeRef().withName(((CodeDef)element).getName()); codeRef.setResultType(element.getResultType()); return codeRef; } if (element instanceof ConceptDef) { ConceptRef conceptRef = of.createConceptRef().withName(((ConceptDef)element).getName()); conceptRef.setResultType(element.getResultType()); return conceptRef; } if (element instanceof IncludeDef) { LibraryRef libraryRef = new LibraryRef(); libraryRef.setLibraryName(((IncludeDef) element).getLocalIdentifier()); return libraryRef; } if (mustResolve) { throw new IllegalArgumentException(String.format("Could not resolve identifier %s in the current library.", identifier)); } return null; } public Expression resolveAccessor(Expression left, String memberIdentifier) { // if left is a LibraryRef // if right is an identifier // right may be an ExpressionRef, a CodeSystemRef, a ValueSetRef, a CodeRef, a ConceptRef, or a ParameterRef -- need to resolve on the referenced library // if left is an ExpressionRef // if right is an identifier // return a Property with the ExpressionRef as source and identifier as Path // if left is a Property // if right is an identifier // modify the Property to append the identifier to the path // if left is an AliasRef // return a Property with a Path and no source, and Scope set to the Alias // if left is an Identifier // return a new Identifier with left as a qualifier // else // throws an error as an unresolved identifier if (left instanceof LibraryRef) { String libraryName = ((LibraryRef)left).getLibraryName(); TranslatedLibrary referencedLibrary = resolveLibrary(libraryName); Element element = referencedLibrary.resolve(memberIdentifier); if (element instanceof ExpressionDef) { checkAccessLevel(libraryName, memberIdentifier, ((ExpressionDef)element).getAccessLevel()); Expression result = of.createExpressionRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(getExpressionDefResultType((ExpressionDef)element)); return result; } if (element instanceof ParameterDef) { checkAccessLevel(libraryName, memberIdentifier, ((ParameterDef)element).getAccessLevel()); Expression result = of.createParameterRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(element.getResultType()); return result; } if (element instanceof ValueSetDef) { checkAccessLevel(libraryName, memberIdentifier, ((ValueSetDef)element).getAccessLevel()); ValueSetRef result = of.createValueSetRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(element.getResultType()); return result; } if (element instanceof CodeSystemDef) { checkAccessLevel(libraryName, memberIdentifier, ((CodeSystemDef)element).getAccessLevel()); CodeSystemRef result = of.createCodeSystemRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(element.getResultType()); return result; } if (element instanceof CodeDef) { checkAccessLevel(libraryName, memberIdentifier, ((CodeDef)element).getAccessLevel()); CodeRef result = of.createCodeRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(element.getResultType()); return result; } if (element instanceof ConceptDef) { checkAccessLevel(libraryName, memberIdentifier, ((ConceptDef)element).getAccessLevel()); ConceptRef result = of.createConceptRef() .withLibraryName(libraryName) .withName(memberIdentifier); result.setResultType(element.getResultType()); return result; } throw new IllegalArgumentException(String.format("Could not resolve identifier %s in library %s.", memberIdentifier, referencedLibrary.getIdentifier().getId())); } else if (left instanceof AliasRef) { Property result = of.createProperty() .withScope(((AliasRef) left).getName()) .withPath(memberIdentifier); result.setResultType(resolveProperty(left.getResultType(), memberIdentifier)); return result; } else if (left.getResultType() instanceof ListType) { // NOTE: FHIRPath path traversal support // Resolve property access of a list of items as a query: // listValue.property ::= listValue X where X.property is not null return X.property ListType listType = (ListType)left.getResultType(); DataType propertyType = resolveProperty(listType.getElementType(), memberIdentifier); Property accessor = of.createProperty() .withSource(of.createAliasRef().withName("$this")) .withPath(memberIdentifier); accessor.setResultType(propertyType); IsNull isNull = of.createIsNull().withOperand(accessor); isNull.setResultType(resolveTypeName("System", "Boolean")); Not not = of.createNot().withOperand(isNull); not.setResultType(resolveTypeName("System", "Boolean")); // Recreate property, it needs to be accessed twice accessor = of.createProperty() .withSource(of.createAliasRef().withName("$this")) .withPath(memberIdentifier); accessor.setResultType(propertyType); AliasedQuerySource source = of.createAliasedQuerySource().withExpression(left).withAlias("$this"); source.setResultType(left.getResultType()); Query query = of.createQuery() .withSource(source) .withWhere(not) .withReturn(of.createReturnClause().withExpression(accessor)); query.setResultType(new ListType(accessor.getResultType())); if (accessor.getResultType() instanceof ListType) { Flatten result = of.createFlatten().withOperand(query); result.setResultType(accessor.getResultType()); return result; } return query; } else { Property result = of.createProperty() .withSource(left) .withPath(memberIdentifier); result.setResultType(resolveProperty(left.getResultType(), memberIdentifier)); return result; } } private IdentifierRef resolveQueryResultElement(String identifier) { if (queries.size() > 0) { QueryContext query = queries.peek(); if (query.inSortClause() && !query.isSingular()) { DataType sortColumnType = resolveProperty(query.getResultElementType(), identifier, false); if (sortColumnType != null) { IdentifierRef result = new IdentifierRef().withName(identifier); result.setResultType(sortColumnType); return result; } } } return null; } private AliasedQuerySource resolveAlias(String identifier) { for (QueryContext query : queries) { AliasedQuerySource source = query.resolveAlias(identifier); if (source != null) { return source; } } return null; } private Expression resolveQueryThisElement(String identifier) { if (queries.size() > 0) { QueryContext query = queries.peek(); if (query.isImplicit()) { AliasedQuerySource source = resolveAlias("$this"); if (source != null) { AliasRef aliasRef = of.createAliasRef().withName("$this"); if (source.getResultType() instanceof ListType) { aliasRef.setResultType(((ListType)source.getResultType()).getElementType()); } else { aliasRef.setResultType(source.getResultType()); } DataType resultType = resolveProperty(aliasRef.getResultType(), identifier, false); if (resultType != null) { return resolveAccessor(aliasRef, identifier); } } } } return null; } private LetClause resolveQueryLet(String identifier) { for (QueryContext query : queries) { LetClause let = query.resolveLet(identifier); if (let != null) { return let; } } return null; } private OperandRef resolveOperandRef(String identifier) { if (currentFunctionDef != null) { for (OperandDef operand : currentFunctionDef.getOperand()) { if (operand.getName().equals(identifier)) { return (OperandRef)of.createOperandRef() .withName(identifier) .withResultType(operand.getResultType()); } } } return null; } private DataType getExpressionDefResultType(ExpressionDef expressionDef) { // If the current expression context is the same as the expression def context, return the expression def result type. if (currentExpressionContext().equals(expressionDef.getContext())) { return expressionDef.getResultType(); } // If the current expression context is patient, a reference to a population context expression will indicate a full // evaluation of the population context expression, and the result type is the same. if (inPatientContext()) { return expressionDef.getResultType(); } // If the current expression context is population, a reference to a patient context expression will need to be // performed for every patient in the population, so the result type is promoted to a list (if it is not already). if (inPopulationContext()) { // If we are in the source clause of a query, indicate that the source references patient context if (!queries.empty() && queries.peek().inSourceClause()) { queries.peek().referencePatientContext(); } DataType resultType = expressionDef.getResultType(); if (!(resultType instanceof ListType)) { return new ListType(resultType); } else { return resultType; } } throw new IllegalArgumentException(String.format("Invalid context reference from %s context to %s context.", currentExpressionContext(), expressionDef.getContext())); } public void pushExpressionDefinition(String identifier) { if (expressionDefinitions.contains(identifier)) { throw new IllegalArgumentException(String.format("Cannot resolve reference to expression %s because it results in a circular reference.", identifier)); } expressionDefinitions.push(identifier); } public void popExpressionDefinition() { expressionDefinitions.pop(); } public void pushExpressionContext(String context) { expressionContext.push(context); } public void popExpressionContext() { if (expressionContext.empty()) { throw new IllegalStateException("Expression context stack is empty."); } expressionContext.pop(); } public String currentExpressionContext() { if (expressionContext.empty()) { throw new IllegalStateException("Expression context stack is empty."); } return expressionContext.peek(); } public boolean inPatientContext() { return currentExpressionContext().equals("Patient"); } public boolean inPopulationContext() { return currentExpressionContext().equals("Population"); } public boolean inQueryContext() { return queries.size() > 0; } public void pushQueryContext(QueryContext context) { queries.push(context); } public QueryContext popQueryContext() { return queries.pop(); } public QueryContext peekQueryContext() { return queries.peek(); } public void pushExpressionTarget(Expression target) { targets.push(target); } public Expression popExpressionTarget() { return targets.pop(); } public boolean hasExpressionTarget() { return !targets.isEmpty(); } public void beginFunctionDef(FunctionDef functionDef) { currentFunctionDef = functionDef; } public void endFunctionDef() { currentFunctionDef = null; } }
package refinedstorage.tile; import cofh.api.energy.EnergyStorage; import cofh.api.energy.IEnergyReceiver; import io.netty.buffer.ByteBuf; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.common.network.ByteBufUtils; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageBlocks; import refinedstorage.RefinedStorageGui; import refinedstorage.RefinedStorageItems; import refinedstorage.block.BlockController; import refinedstorage.block.EnumControllerType; import refinedstorage.container.ContainerController; import refinedstorage.item.ItemPattern; import refinedstorage.item.ItemWirelessGrid; import refinedstorage.network.GridPullFlags; import refinedstorage.network.MessageWirelessGridItems; import refinedstorage.storage.IStorage; import refinedstorage.storage.IStorageProvider; import refinedstorage.storage.ItemGroup; import refinedstorage.tile.autocrafting.CraftingTask; import refinedstorage.tile.config.IRedstoneModeConfig; import refinedstorage.tile.config.RedstoneMode; import refinedstorage.tile.grid.WirelessGridConsumer; import refinedstorage.util.HandUtils; import refinedstorage.util.InventoryUtils; import java.util.*; public class TileController extends TileBase implements IEnergyReceiver, INetworkTile, IRedstoneModeConfig { public class ClientSideMachine { public ItemStack stack; public int energyUsage; public int x; public int y; public int z; } public static final int ENERGY_CAPACITY = 32000; private List<ItemGroup> itemGroups = new ArrayList<ItemGroup>(); private List<IStorage> storages = new ArrayList<IStorage>(); private List<WirelessGridConsumer> wirelessGridConsumers = new ArrayList<WirelessGridConsumer>(); private List<WirelessGridConsumer> wirelessGridConsumersMarkedForRemoval = new ArrayList<WirelessGridConsumer>(); private RedstoneMode redstoneMode = RedstoneMode.IGNORE; private List<TileMachine> machines = new ArrayList<TileMachine>(); private List<ClientSideMachine> clientSideMachines = new ArrayList<ClientSideMachine>(); private List<CraftingTask> craftingTasks = new ArrayList<CraftingTask>(); private List<CraftingTask> craftingTasksToAdd = new ArrayList<CraftingTask>(); private Set<String> visited = new HashSet<String>(); private EnergyStorage energy = new EnergyStorage(ENERGY_CAPACITY); private int energyUsage; private int wirelessGridRange; private boolean destroyed = false; private long lastEnergyRerender; private boolean machinesHavePosition(List<TileMachine> tiles, BlockPos pos) { for (TileEntity tile : tiles) { if (tile.getPos().getX() == pos.getX() && tile.getPos().getY() == pos.getY() && tile.getPos().getZ() == pos.getZ()) { return true; } } return false; } @Override public void update() { super.update(); if (!worldObj.isRemote && !destroyed) { int lastEnergy = energy.getEnergyStored(); if (ticks % 20 == 0) { if (!isActive()) { disconnectAll(); } else { visited.clear(); List<TileMachine> newMachines = new ArrayList<TileMachine>(); for (EnumFacing dir : EnumFacing.VALUES) { MachineSearcher.search(this, pos.offset(dir), visited, newMachines); } for (TileMachine machine : machines) { if (!machinesHavePosition(newMachines, machine.getPos())) { machine.onDisconnected(); } } int range = 0; int usage = 0; storages.clear(); for (TileMachine machine : newMachines) { if (machine instanceof TileWirelessTransmitter) { range += ((TileWirelessTransmitter) machine).getRange(); } if (machine instanceof IStorageProvider) { ((IStorageProvider) machine).provide(storages); } usage += machine.getEnergyUsage(); if (!machinesHavePosition(machines, machine.getPos())) { machine.onConnected(this); } else { /* This machine is in our machine list, but due to a chunk reload the tile entity would get reset which causes its connected property to reset too (to false). So, if the machine is in our list but not connected (which is the case due to a TE reload) we connect it either way. */ if (!machine.isConnected()) { machine.onConnected(this); } } } wirelessGridRange = range; energyUsage = usage; machines = newMachines; Collections.sort(storages, new Comparator<IStorage>() { @Override public int compare(IStorage s1, IStorage s2) { if (s1.getPriority() == s2.getPriority()) { return 0; } return (s1.getPriority() > s2.getPriority()) ? -1 : 1; } }); syncItems(); } craftingTasks.addAll(craftingTasksToAdd); craftingTasksToAdd.clear(); Iterator<CraftingTask> it = craftingTasks.iterator(); while (it.hasNext()) { CraftingTask task = it.next(); task.attemptCraft(this); if (task.isDone()) { it.remove(); push(task.getResult()); } } } if (isActive()) { switch (getType()) { case NORMAL: energy.extractEnergy(energyUsage, false); break; case CREATIVE: energy.setEnergyStored(energy.getMaxEnergyStored()); break; } } wirelessGridConsumers.removeAll(wirelessGridConsumersMarkedForRemoval); wirelessGridConsumersMarkedForRemoval.clear(); Iterator<WirelessGridConsumer> it = wirelessGridConsumers.iterator(); while (it.hasNext()) { WirelessGridConsumer consumer = it.next(); if (!InventoryUtils.compareStack(consumer.getWirelessGrid(), consumer.getPlayer().getHeldItem(consumer.getHand()))) { consumer.getPlayer().closeScreen(); // This will call onContainerClosed on the Container and remove it from the list } else { if (isActive()) { RefinedStorage.NETWORK.sendTo(new MessageWirelessGridItems(this), (EntityPlayerMP) consumer.getPlayer()); } } } if (lastEnergy != energy.getEnergyStored()) { worldObj.updateComparatorOutputLevel(pos, RefinedStorageBlocks.CONTROLLER); } } } public EnumControllerType getType() { if (worldObj.getBlockState(pos).getBlock() == RefinedStorageBlocks.CONTROLLER) { return (EnumControllerType) worldObj.getBlockState(pos).getValue(BlockController.TYPE); } return EnumControllerType.NORMAL; } public int getWirelessGridRange() { return wirelessGridRange; } public void onDestroyed() { disconnectAll(); destroyed = true; } private void disconnectAll() { for (TileMachine machine : machines) { machine.onDisconnected(); } machines.clear(); } public List<ItemGroup> getItemGroups() { return itemGroups; } public List<CraftingTask> getCraftingTasks() { return craftingTasks; } public void addCraftingTask(CraftingTask task) { craftingTasksToAdd.add(task); } public List<ItemStack> getPatterns() { List<ItemStack> patterns = new ArrayList<ItemStack>(); Iterator<TileMachine> it = machines.iterator(); while (it.hasNext()) { TileMachine machine = it.next(); if (machine instanceof TileCrafter) { TileCrafter crafter = (TileCrafter) machine; for (int i = 0; i < TileCrafter.PATTERN_SLOTS; ++i) { if (crafter.getStackInSlot(i) != null) { patterns.add(crafter.getStackInSlot(i)); } } } } return patterns; } public ItemStack getPatternForItem(ItemStack stack) { for (ItemStack pattern : getPatterns()) { if (InventoryUtils.compareStackNoQuantity(ItemPattern.getResult(pattern), stack)) { return pattern; } } return null; } private void syncItems() { itemGroups.clear(); for (IStorage storage : storages) { storage.addItems(itemGroups); } for (ItemStack pattern : getPatterns()) { ItemGroup patternGroup = new ItemGroup(ItemPattern.getResult(pattern)); patternGroup.setQuantity(0); itemGroups.add(patternGroup); } combineItems(); } private void combineItems() { List<Integer> markedIndexes = new ArrayList<Integer>(); for (int i = 0; i < itemGroups.size(); ++i) { if (markedIndexes.contains(i)) { continue; } ItemGroup group = itemGroups.get(i); // If the item doesn't exist anymore, remove it from storage to avoid crashes if (group.getType() == null) { markedIndexes.add(i); } else { for (int j = i + 1; j < itemGroups.size(); ++j) { if (markedIndexes.contains(j)) { continue; } ItemGroup otherGroup = itemGroups.get(j); if (group.compareNoQuantity(otherGroup)) { group.setQuantity(group.getQuantity() + otherGroup.getQuantity()); markedIndexes.add(j); } } } } List<ItemGroup> markedItems = new ArrayList<ItemGroup>(); for (int i : markedIndexes) { markedItems.add(itemGroups.get(i)); } itemGroups.removeAll(markedItems); } public boolean push(ItemStack stack) { IStorage foundStorage = null; for (IStorage storage : storages) { if (storage.canPush(stack)) { foundStorage = storage; break; } } if (foundStorage == null) { return false; } foundStorage.push(stack); syncItems(); markDirty(); return true; } public ItemStack take(ItemStack stack) { markDirty(); return take(stack, InventoryUtils.COMPARE_DAMAGE | InventoryUtils.COMPARE_NBT); } public ItemStack take(ItemStack stack, int flags) { markDirty(); int requested = stack.stackSize; int receiving = 0; ItemStack newStack = null; for (IStorage storage : storages) { ItemStack took = storage.take(stack, flags); if (took != null) { if (newStack == null) { newStack = took; } else { newStack.stackSize += took.stackSize; } receiving += took.stackSize; } if (requested == receiving) { break; } } syncItems(); return newStack; } public boolean onOpenWirelessGrid(EntityPlayer player, EnumHand hand) { boolean inRange = (int) Math.sqrt(Math.pow(getPos().getX() - player.posX, 2) + Math.pow(getPos().getY() - player.posY, 2) + Math.pow(getPos().getZ() - player.posZ, 2)) < getWirelessGridRange(); if (!inRange) { return false; } wirelessGridConsumers.add(new WirelessGridConsumer(player, hand, player.getHeldItem(hand))); player.openGui(RefinedStorage.INSTANCE, RefinedStorageGui.WIRELESS_GRID, worldObj, HandUtils.getIdFromHand(hand), 0, 0); drainEnergyFromWirelessGrid(player, ItemWirelessGrid.USAGE_OPEN); return true; } public void onCloseWirelessGrid(EntityPlayer player) { WirelessGridConsumer consumer = getWirelessGridConsumer(player); if (consumer != null) { wirelessGridConsumersMarkedForRemoval.add(consumer); } } public void drainEnergyFromWirelessGrid(EntityPlayer player, int energy) { WirelessGridConsumer consumer = getWirelessGridConsumer(player); if (consumer != null) { ItemWirelessGrid item = RefinedStorageItems.WIRELESS_GRID; ItemStack held = consumer.getPlayer().getHeldItem(consumer.getHand()); if (held.getItemDamage() != ItemWirelessGrid.TYPE_CREATIVE) { item.extractEnergy(held, energy, false); if (item.getEnergyStored(held) <= 0) { onCloseWirelessGrid(player); consumer.getPlayer().closeScreen(); } } } } public WirelessGridConsumer getWirelessGridConsumer(EntityPlayer player) { Iterator<WirelessGridConsumer> it = wirelessGridConsumers.iterator(); while (it.hasNext()) { WirelessGridConsumer consumer = it.next(); if (consumer.getPlayer() == player) { return consumer; } } return null; } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); if (nbt.hasKey(RedstoneMode.NBT)) { redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT)); } } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); nbt.setInteger(RedstoneMode.NBT, redstoneMode.id); } @Override public int receiveEnergy(EnumFacing from, int maxReceive, boolean simulate) { return energy.receiveEnergy(maxReceive, simulate); } @Override public int getEnergyStored(EnumFacing from) { return energy.getEnergyStored(); } public int getEnergyScaled(int i) { return (int) ((float) energy.getEnergyStored() / (float) energy.getMaxEnergyStored() * (float) i); } @Override public int getMaxEnergyStored(EnumFacing from) { return energy.getMaxEnergyStored(); } public int getEnergyUsage() { return energyUsage; } @Override public boolean canConnectEnergy(EnumFacing from) { return true; } public boolean isActive() { return energy.getEnergyStored() >= getEnergyUsage() && redstoneMode.isEnabled(worldObj, pos); } @Override public RedstoneMode getRedstoneMode() { return redstoneMode; } @Override public void setRedstoneMode(RedstoneMode mode) { markDirty(); this.redstoneMode = mode; } @Override public BlockPos getMachinePos() { return pos; } public List<ClientSideMachine> getClientSideMachines() { return clientSideMachines; } @Override public void receiveData(ByteBuf buf) { int lastEnergy = energy.getEnergyStored(); energy.setEnergyStored(buf.readInt()); if (lastEnergy != energy.getEnergyStored() && System.currentTimeMillis() - lastEnergyRerender > 3000) { lastEnergyRerender = System.currentTimeMillis(); worldObj.notifyBlockUpdate(pos, worldObj.getBlockState(pos), worldObj.getBlockState(pos), 2 | 4); } } @Override public void sendData(ByteBuf buf) { buf.writeInt(energy.getEnergyStored()); } @Override public void receiveContainerData(ByteBuf buf) { energyUsage = buf.readInt(); redstoneMode = RedstoneMode.getById(buf.readInt()); machines.clear(); List<ClientSideMachine> machines = new ArrayList<ClientSideMachine>(); int size = buf.readInt(); for (int i = 0; i < size; ++i) { int energyUsage = buf.readInt(); int x = buf.readInt(); int y = buf.readInt(); int z = buf.readInt(); ItemStack stack = ByteBufUtils.readItemStack(buf); ClientSideMachine machine = new ClientSideMachine(); machine.x = x; machine.y = y; machine.z = z; machine.energyUsage = energyUsage; machine.stack = stack; machines.add(machine); } clientSideMachines = machines; } @Override public void sendContainerData(ByteBuf buf) { buf.writeInt(isActive() ? energyUsage : 0); buf.writeInt(redstoneMode.id); buf.writeInt(machines.size()); for (TileMachine machine : machines) { buf.writeInt(machine.getEnergyUsage()); buf.writeInt(machine.getPos().getX()); buf.writeInt(machine.getPos().getY()); buf.writeInt(machine.getPos().getZ()); IBlockState state = worldObj.getBlockState(machine.getPos()); ByteBufUtils.writeItemStack(buf, new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state))); } } @Override public Class<? extends Container> getContainer() { return ContainerController.class; } public void handleStoragePull(int id, int flags, EntityPlayerMP player) { if (id < 0 || id > itemGroups.size() - 1) { return; } ItemGroup group = itemGroups.get(id); int quantity = 64; if (GridPullFlags.isPullingHalf(flags) && group.getQuantity() > 1) { quantity = group.getQuantity() / 2; if (quantity > 32) { quantity = 32; } } else if (GridPullFlags.isPullingOne(flags)) { quantity = 1; } else if (GridPullFlags.isPullingWithShift(flags)) { // NO OP, the quantity already set (64) is needed for shift } if (quantity > group.getType().getItemStackLimit(group.toItemStack())) { quantity = group.getType().getItemStackLimit(group.toItemStack()); } ItemStack took = take(group.copy(quantity).toItemStack()); if (took != null) { if (GridPullFlags.isPullingWithShift(flags)) { if (!player.inventory.addItemStackToInventory(took.copy())) { push(took); } } else { player.inventory.setItemStack(took); player.updateHeldItem(); } drainEnergyFromWirelessGrid(player, ItemWirelessGrid.USAGE_PULL); } } public void handleStoragePush(int playerSlot, boolean one, EntityPlayerMP player) { ItemStack stack; if (playerSlot == -1) { stack = player.inventory.getItemStack().copy(); if (one) { stack.stackSize = 1; } } else { stack = player.inventory.getStackInSlot(playerSlot); } if (stack != null) { boolean success = push(stack); if (success) { if (playerSlot == -1) { if (one) { player.inventory.getItemStack().stackSize if (player.inventory.getItemStack().stackSize == 0) { player.inventory.setItemStack(null); } } else { player.inventory.setItemStack(null); } player.updateHeldItem(); } else { player.inventory.setInventorySlotContents(playerSlot, null); } } drainEnergyFromWirelessGrid(player, ItemWirelessGrid.USAGE_PUSH); } } public void sendItemGroups(ByteBuf buf) { buf.writeInt(getItemGroups().size()); for (ItemGroup group : getItemGroups()) { group.toBytes(buf, getItemGroups().indexOf(group)); } } public void onCraftingRequested(int id, int quantity) { if (id >= 0 && id < itemGroups.size() && quantity > 0) { while (quantity > 0) { ItemStack pattern = getPatternForItem(itemGroups.get(id).toItemStack()); if (pattern != null) { addCraftingTask(CraftingTask.createFromPattern(pattern)); quantity -= ItemPattern.getResult(pattern).stackSize; } else { break; } } } } }
package scrum.server.admin; import ilarkesto.core.logging.Log; import java.util.ArrayList; import java.util.List; public class SystemConfigDao extends GSystemConfigDao { private static Log log = Log.get(SystemConfigDao.class); public SystemConfig getSystemConfig() { List<SystemConfig> all = new ArrayList<SystemConfig>(getEntities()); if (all.isEmpty()) throw new RuntimeException("SystemConfig entity does not exist"); while (all.size() > 1) throw new RuntimeException("Multiple SystemConfig entities exist"); return all.get(0); } @Override public void ensureIntegrity() { super.ensureIntegrity(); if (getEntities().isEmpty()) { log.warn("SystemConfig entity does not exist. Creating new one."); SystemConfig config = newEntityInstance(); saveEntity(config); } getSystemConfig(); } }
package seedu.emeraldo.logic.parser; import seedu.emeraldo.commons.exceptions.IllegalValueException; import seedu.emeraldo.commons.util.StringUtil; import seedu.emeraldo.logic.commands.*; import static seedu.emeraldo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.emeraldo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern TASK_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("\"(?<description>.+)\"" + "(?<dateTime>((( by )|( on )|( from ))[^ + "(?<tagArguments>(?: #[^#]+)*)"); // variable number of tags private static final Pattern TASK_EDIT_ARGS_FORMAT = Pattern.compile("(?<targetIndex>\\d+)" //index must be digits + "\\s+" //any number of whitespace + "(?<description>(\"[^\"]+\")?)" //quote marks are reserved for start and end of description field + "( )?(?<dateTime>(((by )|(on )|(from ))[^ ); public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher = TASK_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return new AddCommand( matcher.group("description"), matcher.group("dateTime"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" #", "").split(" #")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete task command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the edit person command. * * @param args full command args string * @return the prepared command */ private Command prepareEdit(String args) { final Matcher matcher = TASK_EDIT_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { System.out.println("yoooo"); return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } Optional<Integer> index = parseIndex(matcher.group("targetIndex")); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { String description = matcher.group("description"); if(!description.isEmpty()){ description = description.split("\"")[1]; } String dateTime = matcher.group("dateTime").trim(); if(dateTime.isEmpty()){ dateTime = ""; } return new EditCommand( matcher.group("targetIndex"), description, dateTime); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the select task command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find task command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } }
package org.eclipse.persistence.jaxb.compiler; import java.awt.Image; import java.beans.Introspector; import java.util.ArrayList; import java.util.Collection; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Queue; import java.util.Set; import java.util.Map.Entry; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.namespace.QName; import javax.xml.transform.Source; import org.eclipse.persistence.config.DescriptorCustomizer; import org.eclipse.persistence.core.descriptors.CoreDescriptor; import org.eclipse.persistence.core.mappings.CoreAttributeAccessor; import org.eclipse.persistence.core.mappings.CoreMapping; import org.eclipse.persistence.core.mappings.converters.CoreConverter; import org.eclipse.persistence.core.sessions.CoreProject; import org.eclipse.persistence.core.queries.CoreAttributeGroup; import org.eclipse.persistence.dynamic.DynamicClassLoader; import org.eclipse.persistence.exceptions.DescriptorException; import org.eclipse.persistence.exceptions.JAXBException; import org.eclipse.persistence.internal.core.helper.CoreClassConstants; import org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor; import org.eclipse.persistence.internal.descriptors.InstantiationPolicy; import org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor; import org.eclipse.persistence.internal.descriptors.VirtualAttributeAccessor; import org.eclipse.persistence.internal.jaxb.AccessorFactoryWrapper; import org.eclipse.persistence.internal.jaxb.CustomAccessorAttributeAccessor; import org.eclipse.persistence.internal.jaxb.DefaultElementConverter; import org.eclipse.persistence.internal.jaxb.DomHandlerConverter; import org.eclipse.persistence.internal.jaxb.JAXBElementConverter; import org.eclipse.persistence.internal.jaxb.JAXBElementRootConverter; import org.eclipse.persistence.internal.jaxb.JAXBSetMethodAttributeAccessor; import org.eclipse.persistence.internal.jaxb.JaxbClassLoader; import org.eclipse.persistence.internal.jaxb.MultiArgInstantiationPolicy; import org.eclipse.persistence.internal.jaxb.WrappedValue; import org.eclipse.persistence.internal.jaxb.XMLJavaTypeConverter; import org.eclipse.persistence.internal.jaxb.many.JAXBArrayAttributeAccessor; import org.eclipse.persistence.internal.jaxb.many.ManyValue; import org.eclipse.persistence.internal.jaxb.many.MapValue; import org.eclipse.persistence.internal.jaxb.many.MapValueAttributeAccessor; import org.eclipse.persistence.internal.libraries.asm.ClassWriter; import org.eclipse.persistence.internal.libraries.asm.MethodVisitor; import org.eclipse.persistence.internal.libraries.asm.Opcodes; import org.eclipse.persistence.internal.libraries.asm.Type; import org.eclipse.persistence.internal.oxm.Constants; import org.eclipse.persistence.internal.oxm.NamespaceResolver; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.internal.oxm.mappings.AnyAttributeMapping; import org.eclipse.persistence.internal.oxm.mappings.AnyObjectMapping; import org.eclipse.persistence.internal.oxm.mappings.AnyCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.BinaryDataMapping; import org.eclipse.persistence.internal.oxm.mappings.BinaryDataCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.ChoiceCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.ChoiceObjectMapping; import org.eclipse.persistence.internal.oxm.mappings.CollectionReferenceMapping; import org.eclipse.persistence.internal.oxm.mappings.CompositeCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.CompositeObjectMapping; import org.eclipse.persistence.internal.oxm.mappings.Descriptor; import org.eclipse.persistence.internal.oxm.mappings.DirectCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.DirectMapping; import org.eclipse.persistence.internal.oxm.mappings.Field; import org.eclipse.persistence.internal.oxm.mappings.InverseReferenceMapping; import org.eclipse.persistence.internal.oxm.mappings.Mapping; import org.eclipse.persistence.internal.oxm.mappings.ObjectReferenceMapping; import org.eclipse.persistence.internal.oxm.mappings.TransformationMapping; import org.eclipse.persistence.internal.oxm.mappings.VariableXPathCollectionMapping; import org.eclipse.persistence.internal.oxm.mappings.VariableXPathObjectMapping; import org.eclipse.persistence.internal.oxm.mappings.XMLContainerMapping; import org.eclipse.persistence.internal.queries.ContainerPolicy; import org.eclipse.persistence.internal.security.PrivilegedAccessHelper; import org.eclipse.persistence.jaxb.JAXBEnumTypeConverter; import org.eclipse.persistence.jaxb.TypeMappingInfo; import org.eclipse.persistence.jaxb.javamodel.Helper; import org.eclipse.persistence.jaxb.javamodel.JavaClass; import org.eclipse.persistence.jaxb.javamodel.JavaField; import org.eclipse.persistence.jaxb.javamodel.JavaMethod; import org.eclipse.persistence.jaxb.xmlmodel.XmlNamedAttributeNode; import org.eclipse.persistence.jaxb.xmlmodel.XmlNamedObjectGraph; import org.eclipse.persistence.jaxb.xmlmodel.XmlNamedSubgraph; import org.eclipse.persistence.jaxb.xmlmodel.XmlAbstractNullPolicy; import org.eclipse.persistence.jaxb.xmlmodel.XmlElementWrapper; import org.eclipse.persistence.jaxb.xmlmodel.XmlIsSetNullPolicy; import org.eclipse.persistence.jaxb.xmlmodel.XmlJavaTypeAdapter; import org.eclipse.persistence.jaxb.xmlmodel.XmlNullPolicy; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation; import org.eclipse.persistence.jaxb.xmlmodel.XmlJoinNodes.XmlJoinNode; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlReadTransformer; import org.eclipse.persistence.jaxb.xmlmodel.XmlTransformation.XmlWriteTransformer; import org.eclipse.persistence.mappings.DatabaseMapping; import org.eclipse.persistence.mappings.converters.Converter; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.XMLField; import org.eclipse.persistence.oxm.mappings.FixedMimeTypePolicy; import org.eclipse.persistence.oxm.mappings.UnmarshalKeepAsElementPolicy; import org.eclipse.persistence.oxm.mappings.XMLAnyAttributeMapping; import org.eclipse.persistence.oxm.mappings.XMLAnyCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLAnyObjectMapping; import org.eclipse.persistence.oxm.mappings.XMLBinaryDataCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLBinaryDataMapping; import org.eclipse.persistence.oxm.mappings.XMLChoiceCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLChoiceObjectMapping; import org.eclipse.persistence.oxm.mappings.XMLCollectionReferenceMapping; import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping; import org.eclipse.persistence.oxm.mappings.XMLDirectMapping; import org.eclipse.persistence.oxm.mappings.XMLInverseReferenceMapping; import org.eclipse.persistence.oxm.mappings.XMLMapping; import org.eclipse.persistence.oxm.mappings.XMLObjectReferenceMapping; import org.eclipse.persistence.oxm.mappings.XMLTransformationMapping; import org.eclipse.persistence.oxm.mappings.XMLVariableXPathCollectionMapping; import org.eclipse.persistence.oxm.mappings.XMLVariableXPathObjectMapping; import org.eclipse.persistence.oxm.mappings.converters.XMLListConverter; import org.eclipse.persistence.oxm.mappings.nullpolicy.AbstractNullPolicy; import org.eclipse.persistence.oxm.mappings.nullpolicy.IsSetNullPolicy; import org.eclipse.persistence.oxm.mappings.nullpolicy.NullPolicy; import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType; import org.eclipse.persistence.oxm.schema.XMLSchemaClassPathReference; import org.eclipse.persistence.oxm.schema.XMLSchemaReference; import org.eclipse.persistence.queries.AttributeGroup; import org.eclipse.persistence.sessions.Project; /** * INTERNAL: * <p><b>Purpose:</b>To generate a TopLink OXM Project based on Java Class and TypeInfo information * <p><b>Responsibilities:</b><ul> * <li>Generate a XMLDescriptor for each TypeInfo object</li> * <li>Generate a mapping for each TypeProperty object</li> * <li>Determine the correct mapping type based on the type of each property</li> * <li>Set up Converters on mappings for XmlAdapters or JDK 1.5 Enumeration types.</li> * </ul> * <p>This class is invoked by a Generator in order to create a TopLink Project. * This is generally used by JAXBContextFactory to create the runtime project. A Descriptor will * be generated for each TypeInfo and Mappings generated for each Property. In the case that a * non-transient property's type is a user defined class, a Descriptor and Mappings will be generated * for that class as well. * @see org.eclipse.persistence.jaxb.compiler.Generator * @see org.eclipse.persistence.jaxb.compiler.TypeInfo * @see org.eclipse.persistence.jaxb.compiler.Property * @author mmacivor * @since Oracle TopLink 11.1.1.0.0 * */ public class MappingsGenerator { private static final String ATT = "@"; private static final String TXT = "/text()"; private static String OBJECT_CLASS_NAME = "java.lang.Object"; public static final QName RESERVED_QNAME = new QName("urn:ECLIPSELINK_RESERVEDURI", "RESERVEDNAME"); String outputDir = "."; private HashMap<String, QName> userDefinedSchemaTypes; private Helper helper; private JavaClass jotArrayList; private JavaClass jotHashSet; private JavaClass jotHashMap; private JavaClass jotLinkedList; private JavaClass jotTreeSet; private HashMap<String, PackageInfo> packageToPackageInfoMappings; private HashMap<String, TypeInfo> typeInfo; private HashMap<QName, Class> qNamesToGeneratedClasses; private HashMap<String, Class> classToGeneratedClasses; private HashMap<QName, Class> qNamesToDeclaredClasses; private HashMap<QName, ElementDeclaration> globalElements; private List<ElementDeclaration> localElements; private Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClasses; private Map<MapEntryGeneratedKey, Class> generatedMapEntryClasses; private CoreProject project; private NamespaceResolver globalNamespaceResolver; private boolean isDefaultNamespaceAllowed; private Map<TypeMappingInfo, Class>typeMappingInfoToAdapterClasses; public MappingsGenerator(Helper helper) { this.helper = helper; jotArrayList = helper.getJavaClass(ArrayList.class); jotHashSet = helper.getJavaClass(HashSet.class); jotHashMap = helper.getJavaClass(HashMap.class); jotLinkedList = helper.getJavaClass(LinkedList.class); jotTreeSet = helper.getJavaClass(TreeSet.class); qNamesToGeneratedClasses = new HashMap<QName, Class>(); qNamesToDeclaredClasses = new HashMap<QName, Class>(); classToGeneratedClasses = new HashMap<String, Class>(); globalNamespaceResolver = new org.eclipse.persistence.oxm.NamespaceResolver(); isDefaultNamespaceAllowed = true; } public CoreProject generateProject(ArrayList<JavaClass> typeInfoClasses, HashMap<String, TypeInfo> typeInfo, HashMap<String, QName> userDefinedSchemaTypes, HashMap<String, PackageInfo> packageToPackageInfoMappings, HashMap<QName, ElementDeclaration> globalElements, List<ElementDeclaration> localElements, Map<TypeMappingInfo, Class> typeMappingInfoToGeneratedClass, Map<TypeMappingInfo, Class> typeMappingInfoToAdapterClasses, boolean isDefaultNamespaceAllowed) throws Exception { this.typeInfo = typeInfo; this.userDefinedSchemaTypes = userDefinedSchemaTypes; this.packageToPackageInfoMappings = packageToPackageInfoMappings; this.isDefaultNamespaceAllowed = isDefaultNamespaceAllowed; this.globalElements = globalElements; this.localElements = localElements; this.typeMappingInfoToGeneratedClasses = typeMappingInfoToGeneratedClass; this.typeMappingInfoToAdapterClasses = typeMappingInfoToAdapterClasses; project = new Project(); // Generate descriptors for (JavaClass next : typeInfoClasses) { if (!next.isEnum()) { generateDescriptor(next, project); } } // Setup inheritance for (JavaClass next : typeInfoClasses) { if (!next.isEnum()) { setupInheritance(next); } } // Now create mappings generateMappings(); // Setup AttributeGroups for(JavaClass next : typeInfoClasses) { setupAttributeGroups(next); } // apply customizers if necessary Set<Entry<String, TypeInfo>> entrySet = this.typeInfo.entrySet(); for (Entry<String, TypeInfo> entry : entrySet) { TypeInfo tInfo = entry.getValue(); if (tInfo.getXmlCustomizer() != null) { String customizerClassName = tInfo.getXmlCustomizer(); try { Class customizerClass = PrivilegedAccessHelper.getClassForName(customizerClassName, true, helper.getClassLoader()); DescriptorCustomizer descriptorCustomizer = (DescriptorCustomizer) PrivilegedAccessHelper.newInstanceFromClass(customizerClass); descriptorCustomizer.customize((XMLDescriptor)tInfo.getDescriptor()); } catch (IllegalAccessException iae) { throw JAXBException.couldNotCreateCustomizerInstance(iae, customizerClassName); } catch (InstantiationException ie) { throw JAXBException.couldNotCreateCustomizerInstance(ie, customizerClassName); } catch (ClassCastException cce) { throw JAXBException.invalidCustomizerClass(cce, customizerClassName); } catch (ClassNotFoundException cnfe) { throw JAXBException.couldNotCreateCustomizerInstance(cnfe, customizerClassName); } } } processGlobalElements(project); return project; } private void setupAttributeGroups(JavaClass javaClass) { TypeInfo info = this.typeInfo.get(javaClass.getQualifiedName()); XMLDescriptor descriptor = (XMLDescriptor)info.getDescriptor(); if(!info.getObjectGraphs().isEmpty()) { for(XmlNamedObjectGraph next:info.getObjectGraphs()) { AttributeGroup group = descriptor.getAttributeGroup(next.getName()); Map<String, List<CoreAttributeGroup>> subgraphs = processSubgraphs(next.getXmlNamedSubgraph()); for(XmlNamedAttributeNode nextAttributeNode:next.getXmlNamedAttributeNode()) { if(nextAttributeNode.getSubgraph() == null || nextAttributeNode.getSubgraph().length() == 0) { group.addAttribute(nextAttributeNode.getName()); } else { List<CoreAttributeGroup> nestedGroups = subgraphs.get(nextAttributeNode.getSubgraph()); if(nestedGroups == null || nestedGroups.isEmpty()) { Property property = info.getProperties().get(nextAttributeNode.getName()); if(property == null) { //if there's no property associated with the attributeNode, just ignore it continue; } JavaClass cls = property.getActualType(); TypeInfo referenceType = typeInfo.get(cls.getQualifiedName()); if(referenceType != null) { AttributeGroup targetGroup = (AttributeGroup)referenceType.getDescriptor().getAttributeGroup(nextAttributeNode.getSubgraph()); group.addAttribute(nextAttributeNode.getName(), targetGroup); } else { //TODO: Exception } } else { if(nestedGroups.size() == 1) { group.addAttribute(nextAttributeNode.getName(), nestedGroups.get(0)); } else { group.addAttribute(nextAttributeNode.getName(), nestedGroups); } } } } for(XmlNamedSubgraph nextSubclass:next.getXmlNamedSubclassGraph()) { AttributeGroup subclassGroup = new AttributeGroup(next.getName(), nextSubclass.getType(), true); group.getSubClassGroups().put(nextSubclass.getType(), subclassGroup); for(XmlNamedAttributeNode nextAttributeNode:nextSubclass.getXmlNamedAttributeNode()) { if(nextAttributeNode.getSubgraph() == null || nextAttributeNode.getSubgraph().length() == 0) { subclassGroup.addAttribute(nextAttributeNode.getName()); } else { List<CoreAttributeGroup> nestedGroups = subgraphs.get(nextAttributeNode.getSubgraph()); if(nestedGroups == null || nestedGroups.isEmpty()) { Property property = info.getProperties().get(nextAttributeNode.getName()); JavaClass cls = property.getActualType(); TypeInfo referenceType = typeInfo.get(cls.getQualifiedName()); if(referenceType != null) { AttributeGroup targetGroup = (AttributeGroup)referenceType.getDescriptor().getAttributeGroup(nextAttributeNode.getSubgraph()); subclassGroup.addAttribute(nextAttributeNode.getName(), targetGroup); } else { //TODO: Exception } } else { if(nestedGroups.size() == 1) { subclassGroup.addAttribute(nextAttributeNode.getName(), nestedGroups.get(0)); } else { subclassGroup.addAttribute(nextAttributeNode.getName(), nestedGroups); } } } } } } } } private Map<String, List<CoreAttributeGroup>> processSubgraphs(List<XmlNamedSubgraph> subgraphs) { Map<String, List<CoreAttributeGroup>> subgroups = new HashMap<String, List<CoreAttributeGroup>>(); //Iterate through once and create all the AttributeGroups for(XmlNamedSubgraph next: subgraphs) { String type = next.getType(); if(type == null) { type = "java.lang.Object"; } AttributeGroup group = new AttributeGroup(next.getName(), type, false); if(subgroups.containsKey(group.getName())) { List<CoreAttributeGroup> groups = subgroups.get(group.getName()); groups.add(group); } else { List<CoreAttributeGroup> groups = new ArrayList<CoreAttributeGroup>(1); groups.add(group); subgroups.put(group.getName(), groups); } } //Iterate through a second time to populate the groups and set up links. for(XmlNamedSubgraph next:subgraphs) { List<XmlNamedAttributeNode> attributeNodes = next.getXmlNamedAttributeNode(); List<CoreAttributeGroup> attributeGroups = subgroups.get(next.getName()); if(attributeGroups != null) { for(CoreAttributeGroup group:attributeGroups) { String typeName = next.getType(); if(typeName == null) { typeName = "java.lang.Object"; } if(group.getTypeName().equals(typeName)) { for(XmlNamedAttributeNode attributeNode:attributeNodes) { if(attributeNode.getSubgraph() == null || attributeNode.getSubgraph().length() == 0) { group.addAttribute(attributeNode.getName()); } else { List<CoreAttributeGroup> nestedGroups = subgroups.get(attributeNode.getSubgraph()); if(nestedGroups == null || nestedGroups.size() == 0) { //TODO: Exception or check for root level ones on target class } else { group.addAttribute(attributeNode.getName(), nestedGroups.get(0)); } } } } } } } return subgroups; } public void generateDescriptor(JavaClass javaClass, CoreProject project) { String jClassName = javaClass.getQualifiedName(); TypeInfo info = typeInfo.get(jClassName); if (info.isTransient()){ return; } NamespaceInfo namespaceInfo = this.packageToPackageInfoMappings.get(javaClass.getPackageName()).getNamespaceInfo(); String packageNamespace = namespaceInfo.getNamespace(); String elementName; String namespace; if (javaClass.getSuperclass() != null && javaClass.getSuperclass().getName().equals("javax.xml.bind.JAXBElement")) { generateDescriptorForJAXBElementSubclass(javaClass, project, namespaceInfo.getNamespaceResolverForDescriptor()); return; } Descriptor descriptor = new XMLDescriptor(); org.eclipse.persistence.jaxb.xmlmodel.XmlRootElement rootElem = info.getXmlRootElement(); if (rootElem == null) { try{ elementName = info.getXmlNameTransformer().transformRootElementName(javaClass.getName()); }catch (Exception ex){ throw org.eclipse.persistence.exceptions.JAXBException.exceptionDuringNameTransformation(javaClass.getName(), info.getXmlNameTransformer().getClass().getName(), ex); } namespace = packageNamespace; descriptor.setResultAlwaysXMLRoot(true); } else { elementName = rootElem.getName(); if (elementName.equals(XMLProcessor.DEFAULT)) { try{ elementName = info.getXmlNameTransformer().transformRootElementName(javaClass.getName()); }catch (Exception ex){ throw org.eclipse.persistence.exceptions.JAXBException.exceptionDuringNameTransformation(javaClass.getName(), info.getXmlNameTransformer().getClass().getName(), ex); } } namespace = rootElem.getNamespace(); descriptor.setResultAlwaysXMLRoot(false); } descriptor.setJavaClassName(jClassName); if (info.getFactoryMethodName() != null) { descriptor.getInstantiationPolicy().useFactoryInstantiationPolicy(info.getObjectFactoryClassName(), info.getFactoryMethodName()); } if (namespace.equals(XMLProcessor.DEFAULT)) { namespace = namespaceInfo.getNamespace(); } JavaClass manyValueJavaClass = helper.getJavaClass(ManyValue.class); if (!manyValueJavaClass.isAssignableFrom(javaClass)){ if(namespace.length() != 0) { if(isDefaultNamespaceAllowed && globalNamespaceResolver.getDefaultNamespaceURI() == null && namespace.length() != 0) { if (!namespaceInfo.getNamespaceResolverForDescriptor().getPrefixesToNamespaces().containsValue(namespace)) { globalNamespaceResolver.setDefaultNamespaceURI(namespace); namespaceInfo.getNamespaceResolverForDescriptor().setDefaultNamespaceURI(namespace); } } } if (rootElem == null) { descriptor.setDefaultRootElement(""); } else { if (namespace.length() == 0) { descriptor.setDefaultRootElement(elementName); } else { descriptor.setDefaultRootElement(getQualifiedString(getPrefixForNamespace(namespace, namespaceInfo.getNamespaceResolverForDescriptor()), elementName)); } } } descriptor.setNamespaceResolver(namespaceInfo.getNamespaceResolverForDescriptor()); setSchemaContext(descriptor, info); // set the ClassExtractor class name if necessary if (info.isSetClassExtractorName()) { descriptor.getInheritancePolicy().setClassExtractorName(info.getClassExtractorName()); } // set any user-defined properties if (info.getUserProperties() != null) { descriptor.setProperties(info.getUserProperties()); } if (info.isLocationAware()) { Property locProp = null; Iterator<Property> i = info.getPropertyList().iterator(); while (i.hasNext()) { Property p = i.next(); if (p.getType().getName().equals(Constants.LOCATOR_CLASS_NAME)) { locProp = p; } } if (locProp != null && locProp.isTransient()) { // build accessor // don't make a mapping if (locProp.isMethodProperty()) { MethodAttributeAccessor aa = new MethodAttributeAccessor(); aa.setAttributeName(locProp.getPropertyName()); aa.setSetMethodName(locProp.getSetMethodName()); aa.setGetMethodName(locProp.getGetMethodName()); descriptor.setLocationAccessor(aa); } else { // instance variable property InstanceVariableAttributeAccessor aa = new InstanceVariableAttributeAccessor(); aa.setAttributeName(locProp.getPropertyName()); descriptor.setLocationAccessor(aa); } } } if(!info.getObjectGraphs().isEmpty()) { //create attribute groups for each object graph. //these will be populated later to allow for linking for(XmlNamedObjectGraph next:info.getObjectGraphs()) { AttributeGroup attributeGroup = new AttributeGroup(next.getName(), info.getJavaClassName(), false); ((XMLDescriptor)descriptor).addAttributeGroup(attributeGroup); //process subclass graphs for inheritance //for(NamedSubgraph nextSubclass:next.getNamedSubclassGraph()) { //attributeGroup.insertSubClass(new AttributeGroup(next.getName(), nextSubclass.getType())); } } project.addDescriptor((CoreDescriptor)descriptor); info.setDescriptor(descriptor); } public void generateDescriptorForJAXBElementSubclass(JavaClass javaClass, CoreProject project, NamespaceResolver nsr) { String jClassName = javaClass.getQualifiedName(); TypeInfo info = typeInfo.get(jClassName); Descriptor xmlDescriptor = new XMLDescriptor(); xmlDescriptor.setJavaClassName(jClassName); String[] factoryMethodParamTypes = info.getFactoryMethodParamTypes(); MultiArgInstantiationPolicy policy = new MultiArgInstantiationPolicy(); policy.useFactoryInstantiationPolicy(info.getObjectFactoryClassName(), info.getFactoryMethodName()); policy.setParameterTypeNames(factoryMethodParamTypes); policy.setDefaultValues(new String[]{null}); xmlDescriptor.setInstantiationPolicy(policy); JavaClass paramClass = helper.getJavaClass(factoryMethodParamTypes[0]); boolean isObject = paramClass.getName().equals("java.lang.Object"); if(helper.isBuiltInJavaType(paramClass) && !isObject ){ if(isBinaryData(paramClass)){ BinaryDataMapping mapping = new XMLBinaryDataMapping(); mapping.setAttributeName("value"); mapping.setXPath("."); ((Field)mapping.getField()).setSchemaType(Constants.BASE_64_BINARY_QNAME); mapping.setSetMethodName("setValue"); mapping.setGetMethodName("getValue"); Class attributeClassification = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(factoryMethodParamTypes[0], helper.getClassLoader()); mapping.setAttributeClassification(attributeClassification); mapping.getNullPolicy().setNullRepresentedByEmptyNode(false); mapping.setShouldInlineBinaryData(false); if(mapping.getMimeType() == null) { if(areEquals(paramClass, javax.xml.transform.Source.class)) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/xml")); } else { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/octet-stream")); } } xmlDescriptor.addMapping((CoreMapping)mapping); } else { DirectMapping mapping = new XMLDirectMapping(); mapping.setNullValueMarshalled(true); mapping.setAttributeName("value"); mapping.setGetMethodName("getValue"); mapping.setSetMethodName("setValue"); mapping.setXPath("text()"); Class attributeClassification = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(factoryMethodParamTypes[0], helper.getClassLoader()); mapping.setAttributeClassification(attributeClassification); xmlDescriptor.addMapping((CoreMapping)mapping); } }else if(paramClass.isEnum()){ EnumTypeInfo enumInfo = (EnumTypeInfo)typeInfo.get(paramClass.getQualifiedName()); DirectMapping mapping = new XMLDirectMapping(); mapping.setConverter(buildJAXBEnumTypeConverter(mapping, enumInfo)); mapping.setNullValueMarshalled(true); mapping.setAttributeName("value"); mapping.setGetMethodName("getValue"); mapping.setSetMethodName("setValue"); mapping.setXPath("text()"); Class attributeClassification = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(factoryMethodParamTypes[0], helper.getClassLoader()); mapping.setAttributeClassification(attributeClassification); xmlDescriptor.addMapping((CoreMapping)mapping); }else{ CompositeObjectMapping mapping = new XMLCompositeObjectMapping(); mapping.setAttributeName("value"); mapping.setGetMethodName("getValue"); mapping.setSetMethodName("setValue"); mapping.setXPath("."); if(isObject){ mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); }else{ mapping.setReferenceClassName(factoryMethodParamTypes[0]); } xmlDescriptor.addMapping((CoreMapping)mapping); } xmlDescriptor.setNamespaceResolver(nsr); setSchemaContext(xmlDescriptor, info); project.addDescriptor((CoreDescriptor)xmlDescriptor); info.setDescriptor(xmlDescriptor); } private void setSchemaContext(Descriptor desc, TypeInfo info) { XMLSchemaClassPathReference schemaRef = new XMLSchemaClassPathReference(); if (info.getClassNamespace() == null || info.getClassNamespace().equals("")) { schemaRef.setSchemaContext("/" + info.getSchemaTypeName()); schemaRef.setSchemaContextAsQName(new QName(info.getSchemaTypeName())); } else { String prefix = desc.getNonNullNamespaceResolver().resolveNamespaceURI(info.getClassNamespace()); if (prefix != null && !prefix.equals("")) { schemaRef.setSchemaContext("/" + prefix + ":" + info.getSchemaTypeName()); schemaRef.setSchemaContextAsQName(new QName(info.getClassNamespace(), info.getSchemaTypeName(), prefix)); } else { String generatedPrefix =getPrefixForNamespace(info.getClassNamespace(), desc.getNonNullNamespaceResolver(), false); schemaRef.setSchemaContext("/" + getQualifiedString(generatedPrefix, info.getSchemaTypeName())); if(generatedPrefix == null || generatedPrefix.equals(Constants.EMPTY_STRING)){ schemaRef.setSchemaContextAsQName(new QName(info.getClassNamespace(), info.getSchemaTypeName())); }else{ schemaRef.setSchemaContextAsQName(new QName(info.getClassNamespace(), info.getSchemaTypeName(), generatedPrefix)); } } } // the default type is complex; need to check for simple type case if (info.isEnumerationType() || (info.getPropertyNames().size() == 1 && helper.isAnnotationPresent(info.getProperties().get(info.getPropertyNames().get(0)).getElement(), XmlValue.class))) { schemaRef.setType(XMLSchemaReference.SIMPLE_TYPE); } desc.setSchemaReference(schemaRef); } /** * Generate a mapping for a given Property. * * @param property * @param descriptor * @param namespaceInfo * @return newly created mapping */ public Mapping generateMapping(Property property, Descriptor descriptor, JavaClass descriptorJavaClass, NamespaceInfo namespaceInfo) { if (property.isSetXmlJavaTypeAdapter()) { // if we are dealing with a reference, generate mapping and return if (property.isReference()) { return generateMappingForReferenceProperty(property, descriptor, namespaceInfo); } XmlJavaTypeAdapter xja = property.getXmlJavaTypeAdapter(); JavaClass adapterClass = helper.getJavaClass(xja.getValue()); JavaClass valueType = null; String sValType = xja.getValueType(); if (sValType.equals("javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter.DEFAULT")) { valueType = property.getActualType(); } else { valueType = helper.getJavaClass(xja.getValueType()); } Mapping mapping; boolean isArray = property.getType().isArray() && !property.getType().getRawName().equals("byte[]"); // if the value type is something we have a descriptor for, create // a composite mapping if(property.isChoice()) { if(helper.isCollectionType(property.getType()) || property.getType().isArray()) { mapping = generateChoiceCollectionMapping(property, descriptor, namespaceInfo); ((ChoiceCollectionMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } else { mapping = generateChoiceMapping(property, descriptor, namespaceInfo); ((ChoiceObjectMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } else if (typeInfo.containsKey(valueType.getQualifiedName())) { TypeInfo reference = typeInfo.get(valueType.getQualifiedName()); if (helper.isCollectionType(property.getType())) { if (reference.isEnumerationType()) { mapping = generateEnumCollectionMapping(property, descriptor, namespaceInfo, (EnumTypeInfo) reference); XMLJavaTypeConverter converter = new XMLJavaTypeConverter(adapterClass.getQualifiedName()); converter.setNestedConverter(((DirectCollectionMapping)mapping).getValueConverter()); ((DirectCollectionMapping)mapping).setValueConverter(converter); } else { if(property.getVariableAttributeName() !=null){ mapping = generateVariableXPathCollectionMapping(property, descriptor, namespaceInfo, valueType); ((VariableXPathCollectionMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); }else{ mapping = generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, valueType.getQualifiedName()); ((CompositeCollectionMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } } else { if (reference.isEnumerationType()) { mapping = generateDirectEnumerationMapping(property, descriptor, namespaceInfo, (EnumTypeInfo) reference); XMLJavaTypeConverter converter = new XMLJavaTypeConverter(adapterClass.getQualifiedName()); converter.setNestedConverter(((DirectMapping)mapping).getConverter()); ((DirectMapping)mapping).setConverter(converter); } else if (property.isInverseReference()) { mapping = generateInverseReferenceMapping(property, descriptor, namespaceInfo); } else { if(property.getVariableAttributeName() !=null){ mapping = generateVariableXPathObjectMapping(property, descriptor, namespaceInfo, valueType); ((VariableXPathObjectMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); }else{ mapping = generateCompositeObjectMapping(property, descriptor, namespaceInfo, valueType.getQualifiedName()); ((CompositeObjectMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } } } else { // no descriptor for value type if (property.isAny()) { if (helper.isCollectionType(property.getType())){ mapping = generateAnyCollectionMapping(property, descriptor, namespaceInfo, property.isMixedContent()); ((AnyCollectionMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } else { mapping = generateAnyObjectMapping(property, descriptor, namespaceInfo); ((AnyObjectMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } else if (helper.isCollectionType(property.getType()) || isArray) { if (property.isSwaAttachmentRef() || property.isMtomAttachment()) { mapping = generateBinaryDataCollectionMapping(property, descriptor, namespaceInfo); ((BinaryDataCollectionMapping) mapping).setValueConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } else{ mapping = generateDirectCollectionMapping(property, descriptor, namespaceInfo); if(adapterClass.getQualifiedName().equals(CollapsedStringAdapter.class.getName())) { ((DirectCollectionMapping)mapping).setCollapsingStringValues(true); } else if(adapterClass.getQualifiedName().equals(NormalizedStringAdapter.class.getName())) { ((DirectCollectionMapping)mapping).setNormalizingStringValues(true); } else { ((DirectCollectionMapping) mapping).setValueConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } } else if (property.isSwaAttachmentRef() || property.isMtomAttachment()) { mapping = generateBinaryMapping(property, descriptor, namespaceInfo); ((BinaryDataMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } else { if (!property.isAttribute() && areEquals(valueType, Object.class) || property.isTyped()){ mapping = generateCompositeObjectMapping(property, descriptor, namespaceInfo, null); ((CompositeObjectMapping)mapping).setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); ((CompositeObjectMapping)mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); return mapping; } mapping = generateDirectMapping(property, descriptor, namespaceInfo); if(adapterClass.getQualifiedName().equals(CollapsedStringAdapter.class.getName())) { ((DirectMapping)mapping).setCollapsingStringValues(true); } else if(adapterClass.getQualifiedName().equals(NormalizedStringAdapter.class.getName())) { ((DirectMapping)mapping).setNormalizingStringValues(true); } else { ((DirectMapping) mapping).setConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } } } return mapping; } if (property.getVariableAttributeName() != null){ if (helper.isCollectionType(property.getType()) || property.getType().isArray() || property.isMap()){ return generateVariableXPathCollectionMapping(property, descriptor, namespaceInfo, property.getActualType()); }else{ return generateVariableXPathObjectMapping(property, descriptor, namespaceInfo, property.getActualType()); } } if (property.isSetXmlJoinNodes()) { if (helper.isCollectionType(property.getType())) { return generateXMLCollectionReferenceMapping(property, descriptor, namespaceInfo, property.getActualType()); } return generateXMLObjectReferenceMapping(property, descriptor, namespaceInfo, property.getType()); } if (property.isXmlTransformation()) { return generateTransformationMapping(property, descriptor, namespaceInfo); } if (property.isChoice()) { if (helper.isCollectionType(property.getType()) || property.getType().isArray()) { return generateChoiceCollectionMapping(property, descriptor, namespaceInfo); } return generateChoiceMapping(property, descriptor, namespaceInfo); } if (property.isInverseReference()) { return generateInverseReferenceMapping(property, descriptor, namespaceInfo); } if (property.isReference()) { return generateMappingForReferenceProperty(property, descriptor, namespaceInfo); } if (property.isAny()) { if (helper.isCollectionType(property.getType()) || property.getType().isArray()){ return generateAnyCollectionMapping(property, descriptor, namespaceInfo, property.isMixedContent()); } return generateAnyObjectMapping(property, descriptor, namespaceInfo); } if (property.isMap()){ if (property.isAnyAttribute()) { return generateAnyAttributeMapping(property, descriptor, namespaceInfo); } return generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, null); } if (helper.isCollectionType(property.getType())) { return generateCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo); } JavaClass referenceClass = property.getType(); String referenceClassName = referenceClass.getRawName(); if (referenceClass.isArray() && !referenceClassName.equals("byte[]")){ JavaClass componentType = referenceClass.getComponentType(); TypeInfo reference = typeInfo.get(componentType.getName()); if (reference != null && reference.isEnumerationType()) { return generateEnumCollectionMapping(property, descriptor, namespaceInfo,(EnumTypeInfo) reference); } if (areEquals(componentType, Object.class)){ CompositeCollectionMapping mapping = generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, null); mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); return mapping; } if (reference != null || componentType.isArray()){ if (property.isXmlIdRef() || property.isSetXmlJoinNodes()) { return generateXMLCollectionReferenceMapping(property, descriptor, namespaceInfo, componentType); } return generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, componentType.getQualifiedName()); } return generateDirectCollectionMapping(property, descriptor, namespaceInfo); } if (property.isXmlIdRef()) { return generateXMLObjectReferenceMapping(property, descriptor, namespaceInfo, referenceClass); } TypeInfo reference = typeInfo.get(referenceClass.getQualifiedName()); if (reference != null) { if (reference.isEnumerationType()) { return generateDirectEnumerationMapping(property, descriptor, namespaceInfo, (EnumTypeInfo) reference); } if (property.isXmlLocation()) { CompositeObjectMapping locationMapping = generateCompositeObjectMapping(property, descriptor, namespaceInfo, referenceClass.getQualifiedName()); reference.getDescriptor().setInstantiationPolicy(new NullInstantiationPolicy()); descriptor.setLocationAccessor((CoreAttributeAccessor)locationMapping.getAttributeAccessor()); return locationMapping; } else { return generateCompositeObjectMapping(property, descriptor, namespaceInfo, referenceClass.getQualifiedName()); } } if (property.isSwaAttachmentRef() || property.isMtomAttachment()) { return generateBinaryMapping(property, descriptor, namespaceInfo); } if (referenceClass.getQualifiedName().equals(OBJECT_CLASS_NAME) && !property.isAttribute() || property.isTyped() ) { CompositeObjectMapping coMapping = generateCompositeObjectMapping(property, descriptor, namespaceInfo, null); coMapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); return coMapping; } if (property.isXmlLocation()) { return null; } return generateDirectMapping(property, descriptor, namespaceInfo); } private Mapping generateVariableXPathCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, JavaClass actualType) { XMLVariableXPathCollectionMapping mapping = new XMLVariableXPathCollectionMapping(); mapping.setAttributeName(property.getPropertyName()); if(property.isMap()){ actualType = property.getValueType(); } initializeXMLContainerMapping(mapping, property.getType().isArray()); initializeXMLMapping(mapping, property); initializeVariableXPathMapping(mapping, property, actualType); if (property.getXmlPath() != null) { mapping.setField(new XMLField(property.getXmlPath())); } else { if (property.isSetXmlElementWrapper()) { mapping.setField((XMLField)getXPathForField(property, namespaceInfo, false, true)); } } if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); JavaClass componentType = collectionType.getComponentType(); if(componentType.isArray()) { JavaClass baseComponentType = getBaseComponentType(componentType); if (baseComponentType.isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(baseComponentType.getRawName()); accessor.setComponentClass(primitiveClass); } else { accessor.setComponentClassName(baseComponentType.getQualifiedName()); } } else { accessor.setComponentClassName(componentType.getQualifiedName()); } mapping.setAttributeAccessor(accessor); } if(property.isMap()){ JavaClass mapType = property.getType(); if(mapType.isInterface()){ mapping.useMapClass("java.util.HashMap"); }else{ mapping.useMapClass(property.getType().getName()); } }else{ collectionType = containerClassImpl(collectionType); mapping.useCollectionClass(helper.getClassForJavaClass(collectionType)); } return mapping; } private Mapping generateVariableXPathObjectMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, JavaClass actualType) { XMLVariableXPathObjectMapping mapping = new XMLVariableXPathObjectMapping(); initializeXMLMapping(mapping, property); initializeVariableXPathMapping(mapping, property, actualType); // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else { NullPolicy nullPolicy = (NullPolicy) mapping.getNullPolicy(); nullPolicy.setSetPerformedForAbsentNode(false); if(property.isNillable()) { nullPolicy.setNullRepresentedByXsiNil(true); nullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } } if (property.getXmlPath() != null) { mapping.setField(new XMLField(property.getXmlPath())); } else { if (property.isSetXmlElementWrapper()) { mapping.setField((XMLField)getXPathForField(property, namespaceInfo, false, true)); } } return mapping; } private void initializeVariableXPathMapping(VariableXPathObjectMapping mapping, Property property, JavaClass actualType){ String variableAttributeName = property.getVariableAttributeName(); TypeInfo refInfo = typeInfo.get(actualType.getName()); if(refInfo == null){ throw JAXBException.unknownTypeForVariableNode(actualType.getName()); } Property refProperty = refInfo.getProperties().get(variableAttributeName); while(refProperty == null){ JavaClass superClass = CompilerHelper.getNextMappedSuperClass(actualType, typeInfo, helper); if (superClass != null){ refInfo = typeInfo.get(superClass.getName()); refProperty = refInfo.getProperties().get(variableAttributeName); }else{ break; } } if(refProperty == null){ throw JAXBException.unknownPropertyForVariableNode(variableAttributeName, actualType.getName()); } String refPropertyType = refProperty.getActualType().getQualifiedName(); if(!(refPropertyType.equals("java.lang.String") || refPropertyType.equals("javax.xml.namespace.QName"))){ throw JAXBException.invalidTypeForVariableNode(variableAttributeName, refPropertyType, actualType.getName()); } if (refProperty.isMethodProperty()) { if (refProperty.getGetMethodName() == null) { // handle case of set with no get method String paramTypeAsString = refProperty.getType().getName(); JAXBSetMethodAttributeAccessor accessor = new JAXBSetMethodAttributeAccessor(paramTypeAsString, helper.getClassLoader()); accessor.setIsReadOnly(true); accessor.setSetMethodName(refProperty.getSetMethodName()); mapping.setIsReadOnly(true); accessor.setAttributeName("thingBLAH"); mapping.setVariableAttributeAccessor(accessor); } else if (refProperty.getSetMethodName() == null) { mapping.setVariableGetMethodName(refProperty.getGetMethodName()); } else { mapping.setVariableGetMethodName(refProperty.getGetMethodName()); mapping.setVariableSetMethodName(refProperty.getSetMethodName()); } }else{ mapping.setVariableAttributeName(property.getVariableAttributeName()); } if(property.getVariableClassName() != null){ mapping.setReferenceClassName(property.getVariableClassName()); }else{ mapping.setReferenceClassName(actualType.getQualifiedName()); } mapping.setAttribute(property.isVariableNodeAttribute()); } private InverseReferenceMapping generateInverseReferenceMapping(Property property, Descriptor descriptor, NamespaceInfo namespace) { InverseReferenceMapping invMapping = new XMLInverseReferenceMapping(); boolean isCollection = helper.isCollectionType(property.getType()); if (isCollection) { invMapping.setReferenceClassName(property.getGenericType().getQualifiedName()); } else { invMapping.setReferenceClassName(property.getType().getQualifiedName()); } invMapping.setAttributeName(property.getPropertyName()); String setMethodName = property.getInverseReferencePropertySetMethodName(); String getMethodName = property.getInverseReferencePropertyGetMethodName(); if (setMethodName != null && !setMethodName.equals(Constants.EMPTY_STRING)) { invMapping.setSetMethodName(setMethodName); } if (getMethodName != null && !getMethodName.equals(Constants.EMPTY_STRING)) { invMapping.setGetMethodName(getMethodName); } invMapping.setMappedBy(property.getInverseReferencePropertyName()); if (isCollection) { JavaClass collectionType = property.getType(); collectionType = containerClassImpl(collectionType); invMapping.useCollectionClass(org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(collectionType.getQualifiedName(), helper.getClassLoader())); } if(property.isWriteableInverseReference()){ if(isCollection){ JavaClass descriptorClass = helper.getJavaClass(descriptor.getJavaClassName()); invMapping.setInlineMapping((XMLCompositeCollectionMapping)generateCompositeCollectionMapping(property, descriptor, descriptorClass, namespace, invMapping.getReferenceClassName())); }else{ invMapping.setInlineMapping((XMLCompositeObjectMapping)generateCompositeObjectMapping(property, descriptor, namespace, invMapping.getReferenceClassName())); } } return invMapping; } /** * Generate an XMLTransformationMapping based on a given Property. * * @param property * @param descriptor * @param namespace * @return */ public TransformationMapping generateTransformationMapping(Property property, Descriptor descriptor, NamespaceInfo namespace) { TransformationMapping mapping = new XMLTransformationMapping(); if (property.isMethodProperty()) { if (property.getGetMethodName() == null) { // handle case of set with no get method String paramTypeAsString = property.getType().getName(); mapping.setAttributeAccessor(new JAXBSetMethodAttributeAccessor(paramTypeAsString, helper.getClassLoader())); mapping.setSetMethodName(property.getSetMethodName()); } else if (property.getSetMethodName() == null) { mapping.setGetMethodName(property.getGetMethodName()); } else { mapping.setSetMethodName(property.getSetMethodName()); mapping.setGetMethodName(property.getGetMethodName()); } } // handle transformation if (property.isSetXmlTransformation()) { XmlTransformation xmlTransformation = property.getXmlTransformation(); mapping.setIsOptional(xmlTransformation.isOptional()); // handle transformer(s) if (xmlTransformation.isSetXmlReadTransformer()) { // handle read transformer mapping.setAttributeName(property.getPropertyName()); XmlReadTransformer readTransformer = xmlTransformation.getXmlReadTransformer(); if (readTransformer.isSetTransformerClass()) { mapping.setAttributeTransformerClassName(xmlTransformation.getXmlReadTransformer().getTransformerClass()); } else { mapping.setAttributeTransformation(xmlTransformation.getXmlReadTransformer().getMethod()); } } if (xmlTransformation.isSetXmlWriteTransformers()) { // handle write transformer(s) for (XmlWriteTransformer writeTransformer : xmlTransformation.getXmlWriteTransformer()) { if (writeTransformer.isSetTransformerClass()) { mapping.addFieldTransformerClassName(writeTransformer.getXmlPath(), writeTransformer.getTransformerClass()); } else { mapping.addFieldTransformation(writeTransformer.getXmlPath(), writeTransformer.getMethod()); } } } } return mapping; } public ChoiceObjectMapping generateChoiceMapping(Property property, Descriptor descriptor, NamespaceInfo namespace) { ChoiceObjectMapping mapping = new XMLChoiceObjectMapping(); initializeXMLMapping((XMLChoiceObjectMapping)mapping, property); boolean isIdRef = property.isXmlIdRef(); Iterator<Property> choiceProperties = property.getChoiceProperties().iterator(); while (choiceProperties.hasNext()) { Property next = choiceProperties.next(); JavaClass type = next.getType(); JavaClass originalType = next.getType(); Converter converter = null; TypeInfo info = typeInfo.get(type.getName()); if(info != null){ XmlJavaTypeAdapter adapter = info.getXmlJavaTypeAdapter(); if(adapter != null){ String adapterValue = adapter.getValue(); JavaClass adapterClass = helper.getJavaClass(adapterValue); JavaClass theClass = CompilerHelper.getTypeFromAdapterClass(adapterClass, helper); type = theClass; converter = new XMLJavaTypeConverter(adapterClass.getQualifiedName()); } } if (next.getXmlJoinNodes() != null) { // handle XmlJoinNodes List<Field> srcFlds = new ArrayList<Field>(); List<Field> tgtFlds = new ArrayList<Field>(); for (XmlJoinNode xmlJoinNode: next.getXmlJoinNodes().getXmlJoinNode()) { srcFlds.add(new XMLField(xmlJoinNode.getXmlPath())); tgtFlds.add(new XMLField(xmlJoinNode.getReferencedXmlPath())); } mapping.addChoiceElement(srcFlds, type.getQualifiedName(), tgtFlds); } else if (isIdRef) { // handle IDREF String tgtXPath = null; TypeInfo referenceType = typeInfo.get(type.getQualifiedName()); if (null != referenceType && referenceType.isIDSet()) { Property prop = referenceType.getIDProperty(); tgtXPath = getXPathForField(prop, namespace, !prop.isAttribute(), false).getXPath(); } // if the XPath is set (via xml-path) use it, otherwise figure it out Field srcXPath; if (next.getXmlPath() != null) { srcXPath = new XMLField(next.getXmlPath()); } else { srcXPath = getXPathForField(next, namespace, true, false); } mapping.addChoiceElement(srcXPath.getXPath(), type.getQualifiedName(), tgtXPath); } else { Field xpath; if (next.getXmlPath() != null) { xpath = new XMLField(next.getXmlPath()); } else { xpath = getXPathForField(next, namespace, (!(this.typeInfo.containsKey(type.getQualifiedName()))) || next.isMtomAttachment() || type.isEnum(), false); } mapping.addChoiceElement(xpath, type.getQualifiedName()); if(!originalType.getQualifiedName().equals(type.getQualifiedName())) { if(mapping.getClassNameToFieldMappings().get(originalType.getQualifiedName()) == null) { mapping.getClassNameToFieldMappings().put(originalType.getQualifiedName(), xpath); } mapping.addConverter(xpath, converter); } Mapping nestedMapping = (Mapping) mapping.getChoiceElementMappings().get(xpath); if(nestedMapping instanceof BinaryDataMapping){ ((BinaryDataMapping)nestedMapping).getNullPolicy().setNullRepresentedByEmptyNode(false); } if (type.isEnum()) { if(nestedMapping.isAbstractDirectMapping()) { ((DirectMapping)nestedMapping).setConverter(buildJAXBEnumTypeConverter(nestedMapping, (EnumTypeInfo)info)); } } } } return mapping; } public ChoiceCollectionMapping generateChoiceCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespace) { ChoiceCollectionMapping mapping = new XMLChoiceCollectionMapping(); initializeXMLContainerMapping(mapping, property.getType().isArray()); initializeXMLMapping((XMLChoiceCollectionMapping)mapping, property); JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); JavaClass componentType = collectionType.getComponentType(); if(componentType.isArray()) { JavaClass baseComponentType = getBaseComponentType(componentType); if (baseComponentType.isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(baseComponentType.getRawName()); accessor.setComponentClass(primitiveClass); } else { accessor.setComponentClassName(baseComponentType.getQualifiedName()); } } else { accessor.setComponentClassName(componentType.getQualifiedName()); } mapping.setAttributeAccessor(accessor); } collectionType = containerClassImpl(collectionType); mapping.useCollectionClassName(collectionType.getRawName()); if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } boolean isIdRef = property.isXmlIdRef(); Iterator<Property> choiceProperties = property.getChoiceProperties().iterator(); while (choiceProperties.hasNext()) { Property next = choiceProperties.next(); JavaClass type = next.getType(); JavaClass originalType = next.getType(); Converter converter = null; Field xmlField = null; TypeInfo info = typeInfo.get(type.getName()); if(info != null){ XmlJavaTypeAdapter adapter = info.getXmlJavaTypeAdapter(); if(adapter != null){ String adapterValue = adapter.getValue(); JavaClass adapterClass = helper.getJavaClass(adapterValue); JavaClass theClass = CompilerHelper.getTypeFromAdapterClass(adapterClass, helper); type = theClass; converter = new XMLJavaTypeConverter(adapterClass.getQualifiedName()); } } if (next.getXmlJoinNodes() != null) { // handle XmlJoinNodes List<Field> srcFlds = new ArrayList<Field>(); List<Field> tgtFlds = new ArrayList<Field>(); for (XmlJoinNode xmlJoinNode: next.getXmlJoinNodes().getXmlJoinNode()) { srcFlds.add(new XMLField(xmlJoinNode.getXmlPath())); tgtFlds.add(new XMLField(xmlJoinNode.getReferencedXmlPath())); } mapping.addChoiceElement(srcFlds, type.getQualifiedName(), tgtFlds); } else if (isIdRef) { // handle IDREF String tgtXPath = null; TypeInfo referenceType = typeInfo.get(type.getQualifiedName()); if (null != referenceType && referenceType.isIDSet()) { Property prop = referenceType.getIDProperty(); tgtXPath = getXPathForField(prop, namespace, !prop.isAttribute(), false).getXPath(); } // if the XPath is set (via xml-path) use it, otherwise figure it out Field srcXPath; if (next.getXmlPath() != null) { srcXPath = new XMLField(next.getXmlPath()); } else { srcXPath = getXPathForField(next, namespace, true, false); } mapping.addChoiceElement(srcXPath.getXPath(), type.getQualifiedName(), tgtXPath); } else { Field xpath; if (next.getXmlPath() != null) { xpath = new XMLField(next.getXmlPath()); } else { xpath = getXPathForField(next, namespace, (!(this.typeInfo.containsKey(type.getQualifiedName()))) || type.isEnum(), false); } xmlField = xpath; mapping.addChoiceElement(xpath.getName(), type.getQualifiedName()); if(!originalType.getQualifiedName().equals(type.getQualifiedName())) { if(mapping.getClassNameToFieldMappings().get(originalType.getQualifiedName()) == null) { mapping.getClassNameToFieldMappings().put(originalType.getQualifiedName(), xpath); } mapping.addConverter(xpath, converter); } } if(xmlField !=null){ Mapping nestedMapping = (Mapping) mapping.getChoiceElementMappings().get(xmlField); if(nestedMapping.isAbstractCompositeCollectionMapping()){ //handle null policy set via xml metadata if (property.isSetNullPolicy()) { ((CompositeCollectionMapping)nestedMapping).setNullPolicy(getNullPolicyFromProperty(property, namespace.getNamespaceResolverForDescriptor())); } else if (next.isNillable() && property.isNillable()){ ((CompositeCollectionMapping)nestedMapping).getNullPolicy().setNullRepresentedByXsiNil(true); ((CompositeCollectionMapping)nestedMapping).getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } } else if(nestedMapping.isAbstractCompositeDirectCollectionMapping()){ if (next.isSetNullPolicy()) { ((DirectCollectionMapping)nestedMapping).setNullPolicy(getNullPolicyFromProperty(next, namespace.getNamespaceResolverForDescriptor())); } else if (next.isNillable() && property.isNillable()){ ((DirectCollectionMapping)nestedMapping).getNullPolicy().setNullRepresentedByXsiNil(true); ((DirectCollectionMapping)nestedMapping).getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } ((DirectCollectionMapping)nestedMapping).getNullPolicy().setNullRepresentedByEmptyNode(false); if (type.isEnum()) { ((DirectCollectionMapping)nestedMapping).setValueConverter(buildJAXBEnumTypeConverter(nestedMapping, (EnumTypeInfo)info)); } } else if(nestedMapping instanceof BinaryDataCollectionMapping){ if (next.isSetNullPolicy()) { ((BinaryDataCollectionMapping)nestedMapping).setNullPolicy(getNullPolicyFromProperty(next, namespace.getNamespaceResolverForDescriptor())); } else if (next.isNillable() && property.isNillable()){ ((BinaryDataCollectionMapping)nestedMapping).getNullPolicy().setNullRepresentedByXsiNil(true); ((BinaryDataCollectionMapping)nestedMapping).getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } } } } return mapping; } public Mapping generateMappingForReferenceProperty(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { boolean isCollection = helper.isCollectionType(property.getType()) || property.getType().isArray(); Mapping mapping; if (isCollection) { mapping = new XMLChoiceCollectionMapping(); initializeXMLContainerMapping((ChoiceCollectionMapping) mapping, property.getType().isArray()); JavaClass collectionType = property.getType(); collectionType = containerClassImpl(collectionType); ((ChoiceCollectionMapping) mapping).useCollectionClassName(collectionType.getRawName()); JAXBElementRootConverter jaxbERConverter = new JAXBElementRootConverter(Object.class); if (property.isSetXmlJavaTypeAdapter()) { JavaClass adapterClass = helper.getJavaClass(property.getXmlJavaTypeAdapter().getValue()); jaxbERConverter.setNestedConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } ((ChoiceCollectionMapping) mapping).setConverter(jaxbERConverter); if (property.isSetWriteOnly()) { ((ChoiceCollectionMapping) mapping).setIsWriteOnly(property.isWriteOnly()); } if (property.isSetXmlElementWrapper()) { ((ChoiceCollectionMapping) mapping).setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } } else { mapping = new XMLChoiceObjectMapping(); JAXBElementRootConverter jaxbERConverter = new JAXBElementRootConverter(Object.class); if (property.isSetXmlJavaTypeAdapter()) { JavaClass adapterClass = helper.getJavaClass(property.getXmlJavaTypeAdapter().getValue()); jaxbERConverter.setNestedConverter(new XMLJavaTypeConverter(adapterClass.getQualifiedName())); } ((ChoiceObjectMapping) mapping).setConverter(jaxbERConverter); if (property.isSetWriteOnly()) { ((ChoiceObjectMapping) mapping).setIsWriteOnly(property.isWriteOnly()); } } initializeXMLMapping((XMLMapping)mapping, property); List<ElementDeclaration> referencedElements = property.getReferencedElements(); JavaClass propertyType = property.getType(); if (propertyType.isArray()) { JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); accessor.setComponentClassName(property.getType().getComponentType().getQualifiedName()); JavaClass componentType = propertyType.getComponentType(); if(componentType.isArray()) { Class adaptedClass = classToGeneratedClasses.get(componentType.getQualifiedName()); accessor.setAdaptedClassName(adaptedClass.getName()); } mapping.setAttributeAccessor(accessor); } String wrapperXPath = ""; // handle XmlElementWrapper if (property.isSetXmlElementWrapper()) { XmlElementWrapper wrapper = property.getXmlElementWrapper(); String namespace = wrapper.getNamespace(); if (namespace.equals(XMLProcessor.DEFAULT)) { if (namespaceInfo.isElementFormQualified()) { namespace = namespaceInfo.getNamespace(); } else { namespace = ""; } } if (namespace.equals("")) { wrapperXPath += (wrapper.getName() + "/"); } else { String prefix = getPrefixForNamespace(namespace, namespaceInfo.getNamespaceResolver()); wrapperXPath += getQualifiedString(prefix, wrapper.getName() + "/"); } } if(property.isMixedContent() && isCollection) { if(wrapperXPath.length() == 0) { ((ChoiceCollectionMapping)mapping).setMixedContent(true); } else { ((ChoiceCollectionMapping)mapping).setMixedContent(wrapperXPath.substring(0, wrapperXPath.length() - 1)); } } for (ElementDeclaration element:referencedElements) { QName elementName = element.getElementName(); JavaClass pType = element.getJavaType(); String pTypeName = element.getJavaTypeName(); boolean isBinaryType = (areEquals(pType, AnnotationsProcessor.JAVAX_ACTIVATION_DATAHANDLER) || areEquals(pType, byte[].class) || areEquals(pType, Image.class) || areEquals(pType, Source.class) || areEquals(pType, AnnotationsProcessor.JAVAX_MAIL_INTERNET_MIMEMULTIPART)); boolean isText = pType.isEnum() || (!isBinaryType && !(this.typeInfo.containsKey(element.getJavaTypeName())) && !(element.getJavaTypeName().equals(OBJECT_CLASS_NAME))); String xPath = wrapperXPath; Field xmlField = this.getXPathForElement(xPath, elementName, namespaceInfo, isText); //ensure byte[] goes to base64 instead of the default hex. if(helper.getXMLToJavaTypeMap().get(pType.getRawName()) == Constants.BASE_64_BINARY_QNAME) { xmlField.setSchemaType(Constants.BASE_64_BINARY_QNAME); } if(areEquals(pType, Object.class)) { setTypedTextField(xmlField); } Mapping nestedMapping; AbstractNullPolicy nullPolicy = null; if(isCollection){ ChoiceCollectionMapping xmlChoiceCollectionMapping = (ChoiceCollectionMapping) mapping; xmlChoiceCollectionMapping.addChoiceElement(xmlField, pTypeName); nestedMapping = (Mapping) xmlChoiceCollectionMapping.getChoiceElementMappings().get(xmlField); if(nestedMapping.isAbstractCompositeCollectionMapping()){ ((CompositeCollectionMapping)nestedMapping).setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); nullPolicy = ((CompositeCollectionMapping)nestedMapping).getNullPolicy(); } if (nestedMapping.isAbstractCompositeDirectCollectionMapping()) { DirectCollectionMapping nestedCompositeDirectCollectionMapping = (DirectCollectionMapping) nestedMapping; nullPolicy = nestedCompositeDirectCollectionMapping.getNullPolicy(); if(pType.isEnum()) { TypeInfo enumTypeInfo = typeInfo.get(pType.getQualifiedName()); nestedCompositeDirectCollectionMapping.setValueConverter(buildJAXBEnumTypeConverter(nestedCompositeDirectCollectionMapping, (EnumTypeInfo) enumTypeInfo)); } if(element.isList()){ XMLListConverter listConverter = new XMLListConverter(); listConverter.setObjectClassName(pType.getQualifiedName()); ((DirectCollectionMapping)nestedMapping).setValueConverter(listConverter); } }else if(nestedMapping instanceof BinaryDataCollectionMapping){ nullPolicy = ((BinaryDataCollectionMapping)nestedMapping).getNullPolicy(); if(element.isList()){ ((XMLField)((BinaryDataCollectionMapping)nestedMapping).getField()).setUsesSingleNode(true); } } } else { ChoiceObjectMapping xmlChoiceObjectMapping = (ChoiceObjectMapping) mapping; xmlChoiceObjectMapping.addChoiceElement(xmlField, pTypeName); nestedMapping = (Mapping) xmlChoiceObjectMapping.getChoiceElementMappings().get(xmlField); if(pType.isEnum()) { TypeInfo enumTypeInfo = typeInfo.get(pType.getQualifiedName()); ((DirectMapping)nestedMapping).setConverter(buildJAXBEnumTypeConverter(nestedMapping, (EnumTypeInfo) enumTypeInfo)); } if(nestedMapping.isAbstractCompositeObjectMapping()){ ((CompositeObjectMapping)nestedMapping).setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); nullPolicy = ((CompositeObjectMapping)nestedMapping).getNullPolicy(); }else if(nestedMapping instanceof BinaryDataMapping){ nullPolicy = ((BinaryDataMapping)nestedMapping).getNullPolicy(); }else if(nestedMapping instanceof DirectMapping){ nullPolicy = ((DirectMapping)nestedMapping).getNullPolicy(); } } if(nullPolicy != null){ nullPolicy.setNullRepresentedByEmptyNode(false); nullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); nullPolicy.setNullRepresentedByXsiNil(true); } if (!element.isXmlRootElement()) { Class scopeClass = element.getScopeClass(); if (scopeClass == javax.xml.bind.annotation.XmlElementDecl.GLOBAL.class){ scopeClass = JAXBElement.GlobalScope.class; } Class declaredType = null; if(element.getAdaptedJavaType() != null){ declaredType = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(element.getAdaptedJavaType().getQualifiedName(), helper.getClassLoader()); }else{ declaredType = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(pType.getQualifiedName(), helper.getClassLoader()); } JAXBElementConverter converter = new JAXBElementConverter(xmlField, declaredType, scopeClass); if (isCollection){ ChoiceCollectionMapping xmlChoiceCollectionMapping = (ChoiceCollectionMapping) mapping; if(element.getJavaTypeAdapterClass() != null){ converter.setNestedConverter(new XMLJavaTypeConverter(element.getJavaTypeAdapterClass().getName())); }else{ CoreConverter originalConverter = xmlChoiceCollectionMapping.getConverter(xmlField); converter.setNestedConverter(originalConverter); } xmlChoiceCollectionMapping.addConverter(xmlField, converter); } else { ChoiceObjectMapping xmlChoiceObjectMapping = (ChoiceObjectMapping) mapping; if(element.getJavaTypeAdapterClass() != null){ converter.setNestedConverter(new XMLJavaTypeConverter(element.getJavaTypeAdapterClass().getName())); }else{ CoreConverter originalConverter = xmlChoiceObjectMapping.getConverter(xmlField); converter.setNestedConverter(originalConverter); } xmlChoiceObjectMapping.addConverter(xmlField, converter); } } } if(property.isAny()){ if(isCollection){ XMLChoiceCollectionMapping xmlChoiceCollectionMapping = (XMLChoiceCollectionMapping) mapping; xmlChoiceCollectionMapping.setIsAny(true); } } return mapping; } private void setTypedTextField(Field field){ field.setIsTypedTextField(true); if(field.getSchemaType() == null){ field.setSchemaType(Constants.ANY_TYPE_QNAME); } ((XMLField)field).addXMLConversion(Constants.DATE_TIME_QNAME, CoreClassConstants.XML_GREGORIAN_CALENDAR); ((XMLField)field).addXMLConversion(Constants.DATE_QNAME, CoreClassConstants.XML_GREGORIAN_CALENDAR); ((XMLField)field).addXMLConversion(Constants.TIME_QNAME, CoreClassConstants.XML_GREGORIAN_CALENDAR); ((XMLField)field).addJavaConversion(CoreClassConstants.APBYTE, Constants.BASE_64_BINARY_QNAME); ((XMLField)field).addJavaConversion(CoreClassConstants.ABYTE, Constants.BASE_64_BINARY_QNAME); } public AnyCollectionMapping generateAnyCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, boolean isMixed) { AnyCollectionMapping mapping = new XMLAnyCollectionMapping(); initializeXMLContainerMapping(mapping, property.getType().isArray()); initializeXMLMapping((XMLMapping)mapping, property); // if the XPath is set (via xml-path) use it if (property.getXmlPath() != null) { mapping.setField(new XMLField(property.getXmlPath())); } else { if (property.isSetXmlElementWrapper()) { mapping.setField(getXPathForField(property, namespaceInfo, false, true)); } } if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } Class declaredType = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(property.getActualType().getQualifiedName(), helper.getClassLoader()); JAXBElementRootConverter jaxbElementRootConverter = new JAXBElementRootConverter(declaredType); mapping.setConverter(jaxbElementRootConverter); if (property.getDomHandlerClassName() != null) { jaxbElementRootConverter.setNestedConverter(new DomHandlerConverter(property.getDomHandlerClassName())); } if (property.isLax() || property.isReference()) { mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); } else { if (property.isAny()) { mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_ALL_AS_ELEMENT); } else { mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_NONE_AS_ELEMENT); } } mapping.setMixedContent(isMixed); if (isMixed) { mapping.setPreserveWhitespaceForMixedContent(true); } if (property.isAny()) { mapping.setUseXMLRoot(true); } JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); JavaClass componentType = collectionType.getComponentType(); if(componentType.isArray()) { JavaClass baseComponentType = getBaseComponentType(componentType); if (baseComponentType.isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(baseComponentType.getRawName()); accessor.setComponentClass(primitiveClass); } else { accessor.setComponentClassName(baseComponentType.getQualifiedName()); } } else { accessor.setComponentClassName(componentType.getQualifiedName()); } mapping.setAttributeAccessor(accessor); } collectionType = containerClassImpl(collectionType); mapping.useCollectionClass(helper.getClassForJavaClass(collectionType)); return mapping; } public CompositeObjectMapping generateCompositeObjectMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, String referenceClassName) { CompositeObjectMapping mapping = new XMLCompositeObjectMapping(); initializeXMLMapping((XMLMapping)mapping, property); // if the XPath is set (via xml-path) use it; otherwise figure it out mapping.setField((XMLField)getXPathForField(property, namespaceInfo, false, false)); // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else { NullPolicy nullPolicy = (NullPolicy) mapping.getNullPolicy(); nullPolicy.setSetPerformedForAbsentNode(false); if(property.isNillable()) { nullPolicy.setNullRepresentedByXsiNil(true); nullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } } if (referenceClassName == null){ setTypedTextField((Field)mapping.getField()); String defaultValue = property.getDefaultValue(); if (null != defaultValue) { mapping.setConverter(new DefaultElementConverter(defaultValue)); } } else { mapping.setReferenceClassName(referenceClassName); } if(property.isTransientType()){ mapping.setReferenceClassName(Constants.UNKNOWN_OR_TRANSIENT_CLASS); } if (property.isRequired()) { ((Field) mapping.getField()).setRequired(true); } return mapping; } public DirectMapping generateDirectMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { DirectMapping mapping = new XMLDirectMapping(); mapping.setNullValueMarshalled(true); String fixedValue = property.getFixedValue(); if (fixedValue != null) { mapping.setIsWriteOnly(true); } initializeXMLMapping((XMLMapping)mapping, property); // if the XPath is set (via xml-path) use it; otherwise figure it out Field xmlField = getXPathForField(property, namespaceInfo, true, false); mapping.setField(xmlField); if (property.getDefaultValue() != null) { mapping.setNullValue(property.getDefaultValue()); } if (property.isXmlId()) { mapping.setCollapsingStringValues(true); } // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else { if (property.isNillable()){ mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } mapping.getNullPolicy().setNullRepresentedByEmptyNode(false); if (!mapping.getXPath().equals("text()")) { ((NullPolicy) mapping.getNullPolicy()).setSetPerformedForAbsentNode(false); } } if (property.isRequired()) { ((Field) mapping.getField()).setRequired(true); } if (property.getType() != null) { String theClass = null; if (property.isSetXmlJavaTypeAdapter()) { theClass = property.getOriginalType().getQualifiedName(); } else { theClass = property.getType().getQualifiedName(); } // Try to get the actual Class try { JavaClass actualJavaClass = helper.getJavaClass(theClass); Class actualClass = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(actualJavaClass.getQualifiedName(), helper.getClassLoader()); mapping.setAttributeClassification(actualClass); } catch (Exception e) { // Couldn't find Class (Dynamic?), so set class name instead. mapping.setAttributeClassificationName(theClass); } } if (Constants.QNAME_QNAME.equals(property.getSchemaType())){ ((Field) mapping.getField()).setSchemaType(Constants.QNAME_QNAME); } // handle cdata set via metadata if (property.isSetCdata()) { mapping.setIsCDATA(property.isCdata()); } return mapping; } public BinaryDataMapping generateBinaryMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { BinaryDataMapping mapping = new XMLBinaryDataMapping(); initializeXMLMapping((XMLMapping)mapping, property); // if the XPath is set (via xml-path) use it mapping.setField(getXPathForField(property, namespaceInfo, false, false)); if (property.isSwaAttachmentRef()) { ((Field) mapping.getField()).setSchemaType(Constants.SWA_REF_QNAME); mapping.setSwaRef(true); } else if (property.isMtomAttachment()) { Field f = ((Field) mapping.getField()); if (!f.getSchemaType().equals(Constants.HEX_BINARY_QNAME)) { f.setSchemaType(Constants.BASE_64_BINARY_QNAME); } } if (property.isInlineBinaryData()) { mapping.setShouldInlineBinaryData(true); } // use a non-dynamic implementation of MimeTypePolicy to wrap the MIME string if (property.getMimeType() != null) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy(property.getMimeType(),(DatabaseMapping) mapping)); } else { if(areEquals(property.getType(), javax.xml.transform.Source.class)) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/xml", (DatabaseMapping)mapping)); } else if(areEquals(property.getType(), java.awt.Image.class)) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("image/png", (DatabaseMapping)mapping)); } else { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/octet-stream", (DatabaseMapping)mapping)); } } if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else { if (property.isNillable()){ mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } mapping.getNullPolicy().setNullRepresentedByEmptyNode(false); if (!mapping.getXPath().equals("text()")) { ((NullPolicy) mapping.getNullPolicy()).setSetPerformedForAbsentNode(false); } } mapping.setAttributeClassificationName(property.getActualType().getQualifiedName()); return mapping; } public BinaryDataCollectionMapping generateBinaryDataCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { BinaryDataCollectionMapping mapping = new XMLBinaryDataCollectionMapping(); initializeXMLMapping((XMLMapping)mapping, property); initializeXMLContainerMapping(mapping, property.getType().isArray()); if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else if (property.isNillable()){ mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } // if the XPath is set (via xml-path) use it mapping.setField(getXPathForField(property, namespaceInfo, false, false)); if (property.isSwaAttachmentRef()) { ((Field) mapping.getField()).setSchemaType(Constants.SWA_REF_QNAME); mapping.setSwaRef(true); } else if (property.isMtomAttachment()) { Field f = (Field) mapping.getField(); if (!f.getSchemaType().equals(Constants.HEX_BINARY_QNAME)) { f.setSchemaType(Constants.BASE_64_BINARY_QNAME); } } if (property.isInlineBinaryData()) { mapping.setShouldInlineBinaryData(true); } // use a non-dynamic implementation of MimeTypePolicy to wrap the MIME string if (property.getMimeType() != null) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy(property.getMimeType())); } else { if(areEquals(property.getType(), javax.xml.transform.Source.class)) { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/xml")); } else { mapping.setMimeTypePolicy(new FixedMimeTypePolicy("application/octet-stream")); } } JavaClass collectionType = property.getType(); JavaClass itemType = property.getActualType(); if(collectionType != null && helper.isCollectionType(collectionType)){ try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(itemType.getQualifiedName(), false, helper.getClassLoader()); mapping.setAttributeElementClass(declaredClass); }catch (Exception e) { } } collectionType = containerClassImpl(collectionType); mapping.useCollectionClassName(collectionType.getRawName()); return mapping; } public DirectMapping generateDirectEnumerationMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, EnumTypeInfo enumInfo) { DirectMapping mapping = new XMLDirectMapping(); initializeXMLMapping((XMLMapping)mapping, property); mapping.setNullValueMarshalled(true); mapping.setConverter(buildJAXBEnumTypeConverter(mapping, enumInfo)); mapping.setField(getXPathForField(property, namespaceInfo, true, false)); if (!mapping.getXPath().equals("text()")) { ((NullPolicy) mapping.getNullPolicy()).setSetPerformedForAbsentNode(false); } return mapping; } private JAXBEnumTypeConverter buildJAXBEnumTypeConverter(Mapping mapping, EnumTypeInfo enumInfo){ JAXBEnumTypeConverter converter = new JAXBEnumTypeConverter(mapping, enumInfo.getClassName(), false); List<String> fieldNames = enumInfo.getFieldNames(); List<Object> xmlEnumValues = enumInfo.getXmlEnumValues(); for (int i=0; i< fieldNames.size(); i++) { converter.addConversionValue(xmlEnumValues.get(i), fieldNames.get(i)); } return converter; } public Mapping generateCollectionMapping(Property property, Descriptor descriptor, JavaClass descriptorJavaClass, NamespaceInfo namespaceInfo) { // check to see if this should be a composite or direct mapping JavaClass javaClass = property.getActualType(); if (property.isMixedContent()) { return generateAnyCollectionMapping(property, descriptor, namespaceInfo, true); } if (property.isXmlIdRef() || property.isSetXmlJoinNodes()) { return generateXMLCollectionReferenceMapping(property, descriptor, namespaceInfo, javaClass); } if (javaClass != null && typeInfo.get(javaClass.getQualifiedName()) != null) { TypeInfo referenceInfo = typeInfo.get(javaClass.getQualifiedName()); if (referenceInfo.isEnumerationType()) { return generateEnumCollectionMapping(property, descriptor, namespaceInfo,(EnumTypeInfo) referenceInfo); } return generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, javaClass.getQualifiedName()); } if (!property.isAttribute() && javaClass != null && javaClass.getQualifiedName().equals(OBJECT_CLASS_NAME)){ CompositeCollectionMapping ccMapping = generateCompositeCollectionMapping(property, descriptor, descriptorJavaClass, namespaceInfo, null); ccMapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); return ccMapping; } if(isBinaryData(javaClass)){ return generateBinaryDataCollectionMapping(property, descriptor, namespaceInfo); } return generateDirectCollectionMapping(property, descriptor, namespaceInfo); } public DirectCollectionMapping generateEnumCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, EnumTypeInfo info) { DirectCollectionMapping mapping = generateDirectCollectionMapping(property, descriptor, namespaceInfo); mapping.setValueConverter(buildJAXBEnumTypeConverter(mapping, info)); return mapping; } public AnyAttributeMapping generateAnyAttributeMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { AnyAttributeMapping mapping = new XMLAnyAttributeMapping(); initializeXMLMapping((XMLAnyAttributeMapping)mapping, property); initializeXMLContainerMapping(mapping, property.getType().isArray()); // if the XPath is set (via xml-path) use it if (property.getXmlPath() != null) { mapping.setField(new XMLField(property.getXmlPath())); } mapping.setSchemaInstanceIncluded(false); mapping.setNamespaceDeclarationIncluded(false); JavaClass mapType = property.getType(); if (areEquals(mapType, Map.class)) { mapType = jotHashMap; } mapping.useMapClassName(mapType.getRawName()); return mapping; } public AnyObjectMapping generateAnyObjectMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { AnyObjectMapping mapping = new XMLAnyObjectMapping(); initializeXMLMapping((XMLMapping)mapping, property); // if the XPath is set (via xml-path) use it if (property.getXmlPath() != null) { mapping.setField(new XMLField(property.getXmlPath())); } Class declaredType = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(property.getActualType().getQualifiedName(), helper.getClassLoader()); JAXBElementRootConverter jaxbElementRootConverter = new JAXBElementRootConverter(declaredType); mapping.setConverter(jaxbElementRootConverter); if (property.getDomHandlerClassName() != null) { jaxbElementRootConverter.setNestedConverter(new DomHandlerConverter(property.getDomHandlerClassName())); } if (property.isLax()) { mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); } else { mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_ALL_AS_ELEMENT); } if (property.isMixedContent()) { mapping.setMixedContent(true); } else { mapping.setUseXMLRoot(true); } return mapping; } protected boolean areEquals(JavaClass src, Class tgt) { if (src == null || tgt == null) { return false; } return src.getRawName().equals(tgt.getCanonicalName()); } /** * Compares a JavaModel JavaClass to a Class. Equality is based on * the raw name of the JavaClass compared to the canonical * name of the Class. * * @param src * @param tgt * @return */ protected boolean areEquals(JavaClass src, String tgtCanonicalName) { if (src == null || tgtCanonicalName == null) { return false; } return src.getRawName().equals(tgtCanonicalName); } private Class generateMapEntryClassAndDescriptor(Property property, NamespaceResolver nr){ JavaClass keyType = property.getKeyType(); JavaClass valueType = property.getValueType(); if(keyType == null){ keyType = helper.getJavaClass("java.lang.Object"); } if(valueType == null){ valueType = helper.getJavaClass("java.lang.Object"); } String mapEntryClassName = getJaxbClassLoader().nextAvailableGeneratedClassName(); MapEntryGeneratedKey mapKey = new MapEntryGeneratedKey(keyType.getQualifiedName(),valueType.getQualifiedName()); Class generatedClass = getGeneratedMapEntryClasses().get(mapKey); if(generatedClass == null){ generatedClass = generateMapEntryClass(mapEntryClassName, keyType.getQualifiedName(), valueType.getQualifiedName()); getGeneratedMapEntryClasses().put(mapKey, generatedClass); Descriptor desc = new XMLDescriptor(); desc.setJavaClass(generatedClass); desc.addMapping((CoreMapping)generateMappingForType(keyType, Property.DEFAULT_KEY_NAME)); desc.addMapping((CoreMapping)generateMappingForType(valueType, Property.DEFAULT_VALUE_NAME)); desc.setNamespaceResolver(nr); project.addDescriptor((CoreDescriptor)desc); } return generatedClass; } private Class generateMapEntryClass(String className, String keyType, String valueType){ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); String qualifiedInternalClassName = className.replace('.', '/'); String qualifiedInternalKeyClassName = keyType.replace('.', '/'); String qualifiedInternalValueClassName = valueType.replace('.', '/'); String sig = "Ljava/lang/Object;Lorg/eclipse/persistence/internal/jaxb/many/MapEntry<L"+qualifiedInternalKeyClassName+";L"+qualifiedInternalValueClassName+";>;"; cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, qualifiedInternalClassName, sig, "java/lang/Object", new String[] { "org/eclipse/persistence/internal/jaxb/many/MapEntry" }); cw.visitField(Opcodes.ACC_PRIVATE, "key", "L"+qualifiedInternalKeyClassName+";", null, null); cw.visitField(Opcodes.ACC_PRIVATE, "value", "L"+qualifiedInternalValueClassName+";", null, null); MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getKey", "()L"+qualifiedInternalKeyClassName+";", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitFieldInsn(Opcodes.GETFIELD, qualifiedInternalClassName, "key", "L"+qualifiedInternalKeyClassName+";"); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setKey", "(L"+qualifiedInternalKeyClassName+";)V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, qualifiedInternalClassName, "key", "L"+qualifiedInternalKeyClassName+";"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "getValue", "()L"+qualifiedInternalValueClassName+";", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitFieldInsn(Opcodes.GETFIELD, qualifiedInternalClassName, "value", "L"+qualifiedInternalValueClassName+";"); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "setValue", "(L"+qualifiedInternalValueClassName+";)V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitFieldInsn(Opcodes.PUTFIELD, qualifiedInternalClassName, "value", "L"+qualifiedInternalValueClassName+";"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); if(!qualifiedInternalValueClassName.equals("java/lang/Object")){ mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_BRIDGE + Opcodes.ACC_SYNTHETIC, "getValue", "()Ljava/lang/Object;", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, qualifiedInternalClassName, "getValue", "()L"+qualifiedInternalValueClassName+";"); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_BRIDGE + Opcodes.ACC_SYNTHETIC, "setValue", "(Ljava/lang/Object;)V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitTypeInsn(Opcodes.CHECKCAST, qualifiedInternalValueClassName); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, qualifiedInternalClassName, "setValue", "(L"+qualifiedInternalValueClassName+";)V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } if(!qualifiedInternalKeyClassName.equals("java/lang/Object")){ mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_BRIDGE + Opcodes.ACC_SYNTHETIC, "getKey", "()Ljava/lang/Object;", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,qualifiedInternalClassName, "getKey", "()L"+qualifiedInternalKeyClassName+";"); mv.visitInsn(Opcodes.ARETURN); mv.visitMaxs(1, 1); mv.visitEnd(); mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_BRIDGE + Opcodes.ACC_SYNTHETIC, "setKey", "(Ljava/lang/Object;)V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitTypeInsn(Opcodes.CHECKCAST, qualifiedInternalKeyClassName); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, qualifiedInternalClassName, "setKey", "(L"+qualifiedInternalKeyClassName+";)V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } cw.visitEnd(); byte[] classBytes =cw.toByteArray(); Class generatedClass = getJaxbClassLoader().generateClass(className, classBytes); return generatedClass; } private Mapping generateMappingForType(JavaClass theType, String attributeName){ Mapping mapping; boolean typeIsObject = theType.getRawName().equals(OBJECT_CLASS_NAME); TypeInfo info = typeInfo.get(theType.getQualifiedName()); if ((info != null && !(info.isEnumerationType())) || typeIsObject) { mapping = new XMLCompositeObjectMapping(); mapping.setAttributeName(attributeName); ((CompositeObjectMapping)mapping).setXPath(attributeName); if(typeIsObject){ ((CompositeObjectMapping)mapping).setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); setTypedTextField((Field)((CompositeObjectMapping)mapping).getField()); }else{ ((CompositeObjectMapping)mapping).setReferenceClassName(theType.getQualifiedName()); } } else { mapping = new XMLDirectMapping(); mapping.setAttributeName(attributeName); ((DirectMapping)mapping).setNullValueMarshalled(true); ((DirectMapping)mapping).setXPath(attributeName + TXT); QName schemaType = (QName) userDefinedSchemaTypes.get(theType.getQualifiedName()); if (schemaType == null) { schemaType = (QName) helper.getXMLToJavaTypeMap().get(theType); } ((Field)((DirectMapping)mapping).getField()).setSchemaType(schemaType); if(info != null && info.isEnumerationType()) { ((DirectMapping)mapping).setConverter(buildJAXBEnumTypeConverter(mapping, (EnumTypeInfo)info)); } } return mapping; } public CompositeCollectionMapping generateCompositeCollectionMapping(Property property, Descriptor descriptor, JavaClass javaClass, NamespaceInfo namespaceInfo, String referenceClassName) { CompositeCollectionMapping mapping = new XMLCompositeCollectionMapping(); initializeXMLMapping((XMLMapping)mapping, property); initializeXMLContainerMapping(mapping, property.getType().isArray()); JavaClass manyValueJavaClass = helper.getJavaClass(ManyValue.class); if (manyValueJavaClass.isAssignableFrom(javaClass)){ mapping.setReuseContainer(false); } // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else if (property.isNillable()){ mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); JavaClass componentType = collectionType.getComponentType(); if(componentType.isArray()) { Class adaptedClass = classToGeneratedClasses.get(componentType.getName()); referenceClassName = adaptedClass.getName(); accessor.setAdaptedClassName(referenceClassName); JavaClass baseComponentType = getBaseComponentType(componentType); if (baseComponentType.isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(baseComponentType.getRawName()); accessor.setComponentClass(primitiveClass); } else { accessor.setComponentClassName(baseComponentType.getQualifiedName()); } } else { accessor.setComponentClassName(componentType.getQualifiedName()); } mapping.setAttributeAccessor(accessor); }else if (helper.isMapType(property.getType())){ Class generatedClass = generateMapEntryClassAndDescriptor(property, descriptor.getNonNullNamespaceResolver()); referenceClassName = generatedClass.getName(); String mapClassName = property.getType().getRawName(); mapping.setAttributeAccessor(new MapValueAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), generatedClass, mapClassName, helper.getClassLoader())); } collectionType = containerClassImpl(collectionType); mapping.useCollectionClassName(collectionType.getRawName()); // if the XPath is set (via xml-path) use it; otherwise figure it out Field xmlField = getXPathForField(property, namespaceInfo, false, false); if(helper.isMapType(property.getType())){ JavaClass mapValueClass = helper.getJavaClass(MapValue.class); if(mapValueClass.isAssignableFrom(javaClass)){ mapping.setXPath("entry"); }else{ mapping.setXPath(xmlField.getXPath() + "/entry"); } }else{ mapping.setXPath(xmlField.getXPath()); } if (referenceClassName == null){ setTypedTextField((Field)mapping.getField()); } else { mapping.setReferenceClassName(referenceClassName); } if(property.isTransientType()){ mapping.setReferenceClassName(Constants.UNKNOWN_OR_TRANSIENT_CLASS); } if (property.isRequired()) { ((Field) mapping.getField()).setRequired(true); } return mapping; } public DirectCollectionMapping generateDirectCollectionMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo) { DirectCollectionMapping mapping = new XMLCompositeDirectCollectionMapping(); initializeXMLMapping((XMLMapping)mapping, property); initializeXMLContainerMapping(mapping, property.getType().isArray()); JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); String componentClassName = collectionType.getComponentType().getQualifiedName(); if (collectionType.getComponentType().isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(componentClassName); accessor.setComponentClass(primitiveClass); mapping.setAttributeAccessor(accessor); Class declaredClass = XMLConversionManager.getDefaultManager().getObjectClass(primitiveClass); mapping.setAttributeElementClass(declaredClass); } else { accessor.setComponentClassName(componentClassName); mapping.setAttributeAccessor(accessor); JavaClass componentType = collectionType.getComponentType(); try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(componentType.getRawName(), false, helper.getClassLoader()); mapping.setAttributeElementClass(declaredClass); }catch (Exception e) {} } } else if (helper.isCollectionType(collectionType)){ Collection args = collectionType.getActualTypeArguments(); if (args.size() >0){ JavaClass itemType = (JavaClass)args.iterator().next(); try { Class declaredClass = PrivilegedAccessHelper.getClassForName(itemType.getRawName(), false, helper.getClassLoader()); if(declaredClass != String.class){ mapping.setAttributeElementClass(declaredClass); } } catch (Exception e) {} } } collectionType = containerClassImpl(collectionType); mapping.useCollectionClassName(collectionType.getRawName()); if (property.getDefaultValue() != null) { mapping.setNullValue(property.getDefaultValue()); } // if the XPath is set (via xml-path) use it; otherwise figure it out Field xmlField = getXPathForField(property, namespaceInfo, true, false); mapping.setField(xmlField); if (helper.isAnnotationPresent(property.getElement(), XmlMixed.class)) { xmlField.setXPath("text()"); } if (Constants.QNAME_QNAME.equals(property.getSchemaType())){ ((Field) mapping.getField()).setSchemaType(Constants.QNAME_QNAME); } // handle null policy set via xml metadata if (property.isSetNullPolicy()) { mapping.setNullPolicy(getNullPolicyFromProperty(property, namespaceInfo.getNamespaceResolverForDescriptor())); } else if (property.isNillable()){ mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); } mapping.getNullPolicy().setNullRepresentedByEmptyNode(false); if (property.isSetXmlElementWrapper()) { mapping.setWrapperNullPolicy(getWrapperNullPolicyFromProperty(property)); } if (property.isRequired()) { ((Field) mapping.getField()).setRequired(true); } if (property.isXmlElementType() && property.getGenericType()!=null ){ Class theClass = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(property.getGenericType().getQualifiedName(), helper.getClassLoader()); mapping.setAttributeElementClass(theClass); } if (xmlField.getXPathFragment().isAttribute() || property.isXmlList() || xmlField.getXPathFragment().nameIsText()){ mapping.setUsesSingleNode(true); } // handle cdata set via metadata if (property.isSetCdata()) { mapping.setIsCDATA(property.isCdata()); } return mapping; } public String getPrefixForNamespace(String URI, NamespaceResolver namespaceResolver) { return getPrefixForNamespace(URI, namespaceResolver, true); } public String getPrefixForNamespace(String URI, NamespaceResolver namespaceResolver, boolean addPrefixToNR) { String defaultNS = namespaceResolver.getDefaultNamespaceURI(); if(defaultNS != null && URI.equals(defaultNS)){ return null; } Enumeration keys = namespaceResolver.getPrefixes(); while (keys.hasMoreElements()) { String next = (String) keys.nextElement(); String nextUri = namespaceResolver.resolveNamespacePrefix(next); if (nextUri.equals(URI)) { return next; } } if (javax.xml.XMLConstants.XML_NS_URI.equals(URI)) { return javax.xml.XMLConstants.XML_NS_PREFIX; } String prefix = globalNamespaceResolver.resolveNamespaceURI(URI); if(prefix == null){ if(URI.equals(globalNamespaceResolver.getDefaultNamespaceURI())) { namespaceResolver.setDefaultNamespaceURI(URI); return null; } else { //Bug 400536 before generating a new one check other resolvers String suggestedPrefix = null; NamespaceInfo refInfo = getNamespaceInfoForURI(URI); if(refInfo != null && refInfo.getNamespaceResolver() !=null){ suggestedPrefix = refInfo.getNamespaceResolver().resolveNamespaceURI(URI); } if(suggestedPrefix != null){ prefix = globalNamespaceResolver.generatePrefix(suggestedPrefix); } else{ prefix = globalNamespaceResolver.generatePrefix(); } } } String nrUri = namespaceResolver.resolveNamespacePrefix(prefix); while(null != nrUri && !URI.equals(nrUri)){ prefix = globalNamespaceResolver.generatePrefix(); nrUri = namespaceResolver.resolveNamespacePrefix(prefix); } if(addPrefixToNR){ namespaceResolver.put(prefix, URI); } globalNamespaceResolver.put(prefix, URI); return prefix; } /** * Setup inheritance for abstract superclass. * * NOTE: We currently only handle one level of inheritance in this case. * For multiple levels the code will need to be modified. The logic in * generateMappings() that determines when to copy down inherited * methods from the parent class will need to be changed as well. * * @param jClass */ private void setupInheritance(JavaClass jClass) { TypeInfo tInfo = typeInfo.get(jClass.getName()); Descriptor descriptor = tInfo.getDescriptor(); if (descriptor == null) { return; } JavaClass superClass = CompilerHelper.getNextMappedSuperClass(jClass, typeInfo, helper); if (superClass == null){ return; } TypeInfo superTypeInfo = typeInfo.get(superClass.getName()); if (superTypeInfo == null){ return; } Descriptor superDescriptor = superTypeInfo.getDescriptor(); if (superDescriptor != null) { XMLSchemaReference sRef = descriptor.getSchemaReference(); if (sRef == null || sRef.getSchemaContext() == null) { return; } JavaClass rootMappedSuperClass = getRootMappedSuperClass(superClass); TypeInfo rootTypeInfo = typeInfo.get(rootMappedSuperClass.getName()); Descriptor rootDescriptor = rootTypeInfo.getDescriptor(); if (rootDescriptor.getNamespaceResolver() == null) { rootDescriptor.setNamespaceResolver(new org.eclipse.persistence.oxm.NamespaceResolver()); } if (rootDescriptor.getInheritancePolicy().getClassIndicatorField() == null) { Field classIndicatorField; if (rootTypeInfo.isSetXmlDiscriminatorNode()) { classIndicatorField = new XMLField(rootTypeInfo.getXmlDiscriminatorNode()); } else { classIndicatorField = new XMLField(ATT + "type"); classIndicatorField.getXPathFragment().setNamespaceURI(javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI); } rootDescriptor.getInheritancePolicy().setClassIndicatorField(classIndicatorField); } Object sCtx = null; //TypeInfo tInfo = typeInfo.get(jClass.getName()); if (tInfo.isSetXmlDiscriminatorValue()) { sCtx = tInfo.getXmlDiscriminatorValue(); } else if(!tInfo.isAnonymousComplexType()){ sCtx = sRef.getSchemaContextAsQName(); } if(sCtx != null) { descriptor.getInheritancePolicy().setParentClassName(superClass.getName()); rootDescriptor.getInheritancePolicy().addClassNameIndicator(jClass.getName(), sCtx); } Object value = rootDescriptor.getInheritancePolicy().getClassNameIndicatorMapping().get(rootDescriptor.getJavaClassName()); if (value == null){ if (rootTypeInfo.isSetXmlDiscriminatorValue()) { rootDescriptor.getInheritancePolicy().addClassNameIndicator(rootDescriptor.getJavaClassName(), rootTypeInfo.getXmlDiscriminatorValue()); } else { XMLSchemaReference rootSRef = rootDescriptor.getSchemaReference(); if (rootSRef != null && rootSRef.getSchemaContext() != null) { QName rootSCtx = rootSRef.getSchemaContextAsQName(); rootDescriptor.getInheritancePolicy().addClassNameIndicator(rootDescriptor.getJavaClassName(), rootSCtx); } } } rootDescriptor.getInheritancePolicy().setShouldReadSubclasses(true); //Check for attributeGroups Map<String, AttributeGroup> childGroups = ((XMLDescriptor)descriptor).getAttributeGroups(); Map<String, AttributeGroup> parentGroups = ((XMLDescriptor)rootDescriptor).getAttributeGroups(); if(childGroups != null && !(childGroups.isEmpty()) && parentGroups != null && !(parentGroups.isEmpty())) { for(String nextKey:childGroups.keySet()) { AttributeGroup parentGroup = parentGroups.get(nextKey); if(parentGroup != null) { AttributeGroup childGroup = childGroups.get(nextKey); parentGroup.getSubClassGroups().put(descriptor.getJavaClassName(), childGroup); } } } } } private JavaClass getRootMappedSuperClass(JavaClass javaClass){ JavaClass rootMappedSuperClass = javaClass; JavaClass nextMappedSuperClass = rootMappedSuperClass; while(nextMappedSuperClass != null){ nextMappedSuperClass = CompilerHelper.getNextMappedSuperClass(nextMappedSuperClass, this.typeInfo, helper); if(nextMappedSuperClass == null){ return rootMappedSuperClass; } rootMappedSuperClass = nextMappedSuperClass; } return rootMappedSuperClass; } public void generateMappings() { Iterator javaClasses = this.typeInfo.keySet().iterator(); while (javaClasses.hasNext()) { String next = (String)javaClasses.next(); JavaClass javaClass = helper.getJavaClass(next); TypeInfo info = (TypeInfo) this.typeInfo.get(next); if (info.isEnumerationType()) { continue; } NamespaceInfo namespaceInfo = this.packageToPackageInfoMappings.get(javaClass.getPackageName()).getNamespaceInfo(); Descriptor descriptor = info.getDescriptor(); if (descriptor != null) { generateMappings(info, descriptor, javaClass, namespaceInfo); // set primary key fields (if necessary) CoreMapping mapping; // handle XmlID if (info.isIDSet()) { mapping = descriptor.getMappingForAttributeName(info.getIDProperty().getPropertyName()); if (mapping != null) { descriptor.addPrimaryKeyField(mapping.getField()); } } // handle XmlKey if (info.hasXmlKeyProperties()) { for (Property keyProp : info.getXmlKeyProperties()) { mapping = descriptor.getMappingForAttributeName(keyProp.getPropertyName()); if (mapping != null) { descriptor.addPrimaryKeyField(mapping.getField()); } } } } info.postInitialize(); } } /** * Generate mappings for a given TypeInfo. * * @param info * @param descriptor * @param namespaceInfo */ public void generateMappings(TypeInfo info, Descriptor descriptor, JavaClass descriptorJavaClass, NamespaceInfo namespaceInfo) { if(info.isAnonymousComplexType()) { //may need to generate inherited mappings generateInheritedMappingsForAnonymousType(info, descriptor, descriptorJavaClass, namespaceInfo); } List<Property> propertiesInOrder = info.getNonTransientPropertiesInPropOrder(); for (int i = 0; i < propertiesInOrder.size(); i++) { Property next = propertiesInOrder.get(i); if (next != null && (!next.isTransient() || (next.isTransient() && next.isXmlLocation()))) { Mapping mapping = generateMapping(next, descriptor, descriptorJavaClass, namespaceInfo); if (next.isVirtual()) { VirtualAttributeAccessor accessor = new VirtualAttributeAccessor(); accessor.setAttributeName(mapping.getAttributeName()); String getMethod = info.getXmlVirtualAccessMethods().getGetMethod(); String setMethod = info.getXmlVirtualAccessMethods().getSetMethod(); // Check to see if get/set were overridden in the mapping if (mapping.getAttributeAccessor().isMethodAttributeAccessor()) { getMethod = ((MethodAttributeAccessor) mapping.getAttributeAccessor()).getGetMethodName(); setMethod = ((MethodAttributeAccessor) mapping.getAttributeAccessor()).getSetMethodName(); accessor.setValueType(mapping.getAttributeClassification()); } accessor.setGetMethodName(getMethod); accessor.setSetMethodName(setMethod); if (mapping.getAttributeAccessor() instanceof JAXBArrayAttributeAccessor) { JAXBArrayAttributeAccessor jaa = (JAXBArrayAttributeAccessor) mapping.getAttributeAccessor(); jaa.setNestedAccessor(accessor); } else { mapping.setAttributeAccessor(accessor); } } if (mapping != null) { descriptor.addMapping((CoreMapping)mapping); } // set user-defined properties if necessary if (next.isSetUserProperties()) { mapping.setProperties(next.getUserProperties()); } //get package info AccessorFactoryWrapper accessorFactory = info.getXmlAccessorFactory(); if(accessorFactory == null) { accessorFactory = info.getPackageLevelXmlAccessorFactory(); } if(accessorFactory != null) { try { Object accessor = CompilerHelper.createAccessorFor(descriptorJavaClass, next, helper, accessorFactory); if(accessor != null) { CustomAccessorAttributeAccessor attributeAccessor = new CustomAccessorAttributeAccessor(accessor); mapping.setAttributeAccessor(attributeAccessor); } } catch(Exception ex) {} } } next.postInitialize(); } } private void generateInheritedMappingsForAnonymousType(TypeInfo info, Descriptor descriptor, JavaClass descriptorJavaClass, NamespaceInfo namespaceInfo) { List<TypeInfo> mappedParents = new ArrayList<TypeInfo>(); JavaClass next = CompilerHelper.getNextMappedSuperClass(descriptorJavaClass, typeInfo, helper); while(next != null) { TypeInfo nextInfo = this.typeInfo.get(next.getName()); mappedParents.add(0, nextInfo); next = CompilerHelper.getNextMappedSuperClass(helper.getJavaClass(nextInfo.getJavaClassName()), typeInfo, helper); } for(TypeInfo nextInfo:mappedParents) { List<Property> propertiesInOrder = nextInfo.getNonTransientPropertiesInPropOrder(); for (int i = 0; i < propertiesInOrder.size(); i++) { Property nextProp = propertiesInOrder.get(i); if (nextProp != null){ Mapping mapping = generateMapping(nextProp, descriptor, descriptorJavaClass, namespaceInfo); descriptor.addMapping((CoreMapping)mapping); // set user-defined properties if necessary if (nextProp.isSetUserProperties()) { mapping.setProperties(nextProp.getUserProperties()); } } } } } /** * Create an XMLCollectionReferenceMapping and add it to the descriptor. * * @param property * @param descriptor * @param namespaceInfo * @param referenceClass */ public CollectionReferenceMapping generateXMLCollectionReferenceMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, JavaClass referenceClass) { CollectionReferenceMapping mapping = new XMLCollectionReferenceMapping(); initializeXMLMapping((XMLMapping)mapping, property); initializeXMLContainerMapping(mapping, property.getType().isArray()); mapping.setUsesSingleNode(property.isXmlList() || (property.isAttribute() && (property.getXmlPath() == null || !property.getXmlPath().contains("/")))); String referenceClassName = referenceClass.getQualifiedName(); JavaClass collectionType = property.getType(); if (collectionType.isArray()){ JAXBArrayAttributeAccessor accessor = new JAXBArrayAttributeAccessor(mapping.getAttributeAccessor(), mapping.getContainerPolicy(), helper.getClassLoader()); JavaClass componentType = collectionType.getComponentType(); if(componentType.isArray()) { Class adaptedClass = classToGeneratedClasses.get(componentType.getName()); referenceClassName = adaptedClass.getName(); accessor.setAdaptedClassName(referenceClassName); JavaClass baseComponentType = getBaseComponentType(componentType); if (baseComponentType.isPrimitive()){ Class primitiveClass = XMLConversionManager.getDefaultManager().convertClassNameToClass(baseComponentType.getRawName()); accessor.setComponentClass(primitiveClass); } else { accessor.setComponentClassName(baseComponentType.getQualifiedName()); } } else { accessor.setComponentClassName(componentType.getQualifiedName()); } mapping.setAttributeAccessor(accessor); } collectionType = containerClassImpl(collectionType); mapping.useCollectionClassName(collectionType.getRawName()); mapping.setReferenceClassName(referenceClassName); // here we need to setup source/target key field associations if (property.isSetXmlJoinNodes()) { for (XmlJoinNode xmlJoinNode: property.getXmlJoinNodes().getXmlJoinNode()) { validateJoinNode(descriptor.getJavaClassName(), property, xmlJoinNode.getReferencedXmlPath(), referenceClass); mapping.addSourceToTargetKeyFieldAssociation(xmlJoinNode.getXmlPath(), xmlJoinNode.getReferencedXmlPath()); } } else { // here we need to setup source/target key field associations TypeInfo referenceType = typeInfo.get(referenceClass.getQualifiedName()); String tgtXPath = null; if (null != referenceType && referenceType.isIDSet()) { Property prop = referenceType.getIDProperty(); tgtXPath = getXPathForField(prop, namespaceInfo, !prop.isAttribute(), false).getXPath(); } // if the XPath is set (via xml-path) use it Field srcXPath; if (property.getXmlPath() != null) { srcXPath = new XMLField(property.getXmlPath()); } else { srcXPath = getXPathForField(property, namespaceInfo, true, false); } mapping.addSourceToTargetKeyFieldAssociation(srcXPath.getXPath(), tgtXPath); } if (property.getInverseReferencePropertyName() != null) { mapping.getInverseReferenceMapping().setAttributeName(property.getInverseReferencePropertyName()); JavaClass backPointerPropertyType = null; if (property.getInverseReferencePropertyGetMethodName() != null && property.getInverseReferencePropertySetMethodName() != null && !property.getInverseReferencePropertyGetMethodName().equals("") && !property.getInverseReferencePropertySetMethodName().equals("")) { mapping.getInverseReferenceMapping().setGetMethodName(property.getInverseReferencePropertySetMethodName()); mapping.getInverseReferenceMapping().setSetMethodName(property.getInverseReferencePropertySetMethodName()); JavaMethod getMethod = referenceClass.getDeclaredMethod(mapping.getInverseReferenceMapping().getGetMethodName(), new JavaClass[]{}); if (getMethod != null) { backPointerPropertyType = getMethod.getReturnType(); } } else { JavaField backpointerField = referenceClass.getDeclaredField(property.getInverseReferencePropertyName()); if (backpointerField != null) { backPointerPropertyType = backpointerField.getResolvedType(); } } if (helper.isCollectionType(backPointerPropertyType)) { mapping.getInverseReferenceMapping().setContainerPolicy(ContainerPolicy.buildDefaultPolicy()); } } return mapping; } /** * Create an XMLObjectReferenceMapping and add it to the descriptor. * * @param property * @param descriptor * @param namespaceInfo * @param referenceClass */ public ObjectReferenceMapping generateXMLObjectReferenceMapping(Property property, Descriptor descriptor, NamespaceInfo namespaceInfo, JavaClass referenceClass) { ObjectReferenceMapping mapping = new XMLObjectReferenceMapping(); initializeXMLMapping((XMLMapping)mapping, property); mapping.setReferenceClassName(referenceClass.getQualifiedName()); // here we need to setup source/target key field associations if (property.isSetXmlJoinNodes()) { for (XmlJoinNode xmlJoinNode: property.getXmlJoinNodes().getXmlJoinNode()) { validateJoinNode(descriptor.getJavaClassName(), property, xmlJoinNode.getReferencedXmlPath(), referenceClass); mapping.addSourceToTargetKeyFieldAssociation(xmlJoinNode.getXmlPath(), xmlJoinNode.getReferencedXmlPath()); } } else { String tgtXPath = null; TypeInfo referenceType = typeInfo.get(referenceClass.getQualifiedName()); if (null != referenceType && referenceType.isIDSet()) { Property prop = referenceType.getIDProperty(); tgtXPath = getXPathForField(prop, namespaceInfo, !prop.isAttribute(), false).getXPath(); } // if the XPath is set (via xml-path) use it, otherwise figure it out Field srcXPath; if (property.getXmlPath() != null) { srcXPath = new XMLField(property.getXmlPath()); } else { srcXPath = getXPathForField(property, namespaceInfo, true, false); } mapping.addSourceToTargetKeyFieldAssociation(srcXPath.getXPath(), tgtXPath); } if (property.getInverseReferencePropertyName() != null) { mapping.getInverseReferenceMapping().setAttributeName(property.getInverseReferencePropertyName()); JavaClass backPointerPropertyType = null; if (property.getInverseReferencePropertyGetMethodName() != null && property.getInverseReferencePropertySetMethodName() != null && !property.getInverseReferencePropertyGetMethodName().equals("") && !property.getInverseReferencePropertySetMethodName().equals("")) { mapping.getInverseReferenceMapping().setGetMethodName(property.getInverseReferencePropertySetMethodName()); mapping.getInverseReferenceMapping().setSetMethodName(property.getInverseReferencePropertySetMethodName()); JavaMethod getMethod = referenceClass.getDeclaredMethod(mapping.getInverseReferenceMapping().getGetMethodName(), new JavaClass[]{}); if (getMethod != null) { backPointerPropertyType = getMethod.getReturnType(); } } else { JavaField backpointerField = referenceClass.getDeclaredField(property.getInverseReferencePropertyName()); if (backpointerField != null) { backPointerPropertyType = backpointerField.getResolvedType(); } } if (helper.isCollectionType(backPointerPropertyType)) { mapping.getInverseReferenceMapping().setContainerPolicy(ContainerPolicy.buildDefaultPolicy()); } } return mapping; } private void validateJoinNode(String className, Property property, String referencedXmlPath, JavaClass referenceClass) { TypeInfo targetInfo = this.typeInfo.get(referenceClass.getQualifiedName()); NamespaceInfo namespaceInfo = this.packageToPackageInfoMappings.get(referenceClass.getPackageName()).getNamespaceInfo(); Property idProp = targetInfo.getIDProperty(); if(idProp != null) { String idXpath = idProp.getXmlPath(); if(idXpath == null) { idXpath = this.getXPathForField(idProp, namespaceInfo, !idProp.isAttribute(), false).getXPath(); } if (referencedXmlPath.equals(idXpath)) { return; } } boolean matched = false; if (targetInfo.getXmlKeyProperties() != null) { for (Property xmlkeyProperty : targetInfo.getXmlKeyProperties()) { String keyXpath = xmlkeyProperty.getXmlPath(); if(keyXpath == null) { keyXpath = this.getXPathForField(xmlkeyProperty, namespaceInfo, !xmlkeyProperty.isAttribute(), false).getXPath(); } if (referencedXmlPath.equals(keyXpath)) { matched = true; break; } } } if (!matched) { throw JAXBException.invalidReferencedXmlPathOnJoin(className, property.getPropertyName(), referenceClass.getQualifiedName(), referencedXmlPath); } } private String prefixCustomXPath(String unprefixedXPath, Property property, NamespaceInfo nsInfo) { String newXPath = ""; QName schemaName = property.getSchemaName(); String namespace = schemaName.getNamespaceURI(); if (null == namespace || namespace.equals(Constants.EMPTY_STRING)) { return unprefixedXPath; } String prefix = getPrefixForNamespace(namespace, nsInfo.getNamespaceResolverForDescriptor()); if (null == prefix) { return unprefixedXPath; } StringTokenizer st = new StringTokenizer(unprefixedXPath, Constants.XPATH_SEPARATOR); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); if (st.hasMoreTokens()) { if (nextToken.lastIndexOf(Constants.COLON) != -1) { // Token already has a user-supplied prefix newXPath += nextToken; } else { newXPath += prefix + Constants.COLON + nextToken; } newXPath += Constants.XPATH_SEPARATOR; } else { // Last token is text() newXPath += nextToken; } } return newXPath; } public Field getXPathForField(Property property, NamespaceInfo namespaceInfo, boolean isTextMapping, boolean isAny) { Field xmlField = null; String xPath = property.getXmlPath(); if (null != xPath) { String newXPath = prefixCustomXPath(xPath, property, namespaceInfo); xmlField = new XMLField(newXPath); } else { xPath = ""; if (property.isSetXmlElementWrapper()) { XmlElementWrapper wrapper = property.getXmlElementWrapper(); String namespace = wrapper.getNamespace(); if (namespace.equals(XMLProcessor.DEFAULT)) { if (namespaceInfo.isElementFormQualified()) { namespace = namespaceInfo.getNamespace(); } else { namespace = ""; } } if (namespace.equals("")) { xPath += (wrapper.getName() + "/"); } else { String prefix = getPrefixForNamespace(namespace, namespaceInfo.getNamespaceResolverForDescriptor()); xPath += getQualifiedString(prefix, wrapper.getName() + "/"); } if (isAny || property.isMap()) { xPath = xPath.substring(0, xPath.length() - 1); xmlField = new XMLField(xPath); return xmlField; } } if (property.isAttribute()) { if (property.isSetXmlPath()) { xPath += property.getXmlPath(); } else { QName name = property.getSchemaName(); String namespace = name.getNamespaceURI(); if (namespace.equals("")) { xPath += (ATT + name.getLocalPart()); } else { String prefix = getPrefixForNamespace(namespace, namespaceInfo.getNamespaceResolverForDescriptor()); xPath += ATT + getQualifiedString(prefix, name.getLocalPart()); } } xmlField = new XMLField(xPath); } else if (property.isXmlValue()) { if(isBinaryData(property.getActualType())){ xmlField = new XMLField("."); }else{ xmlField = new XMLField("text()"); } } else { QName elementName = property.getSchemaName(); xmlField = getXPathForElement(xPath, elementName, namespaceInfo, isTextMapping); } } QName schemaType = (QName) userDefinedSchemaTypes.get(property.getActualType().getQualifiedName()); if (property.getSchemaType() != null) { schemaType = property.getSchemaType(); } if (schemaType == null) { String propertyActualTypeRawName = property.getActualType().getRawName(); if(QName.class.getCanonicalName().equals(propertyActualTypeRawName)) { schemaType = (QName) helper.getXMLToJavaTypeMap().get(propertyActualTypeRawName); } } if(schemaType !=null && !schemaType.equals (Constants.NORMALIZEDSTRING_QNAME)){ xmlField.setSchemaType(schemaType); } return xmlField; } public Field getXPathForElement(String path, QName elementName, NamespaceInfo namespaceInfo, boolean isText) { String namespace = ""; if (!elementName.getNamespaceURI().equals(Constants.EMPTY_STRING)) { namespace = elementName.getNamespaceURI(); } if (namespace.equals(Constants.EMPTY_STRING)) { path += elementName.getLocalPart(); if (isText) { path += TXT; } } else { String prefix = getPrefixForNamespace(namespace, namespaceInfo.getNamespaceResolverForDescriptor()); path += getQualifiedString(prefix, elementName.getLocalPart()); if (isText) { path += TXT; } } return new XMLField(path); } public Property getXmlValueFieldForSimpleContent(ArrayList<Property> properties) { boolean foundValue = false; boolean foundNonAttribute = false; Property valueField = null; for (Property prop : properties) { if (helper.isAnnotationPresent(prop.getElement(), XmlValue.class)) { foundValue = true; valueField = prop; } else if (!helper.isAnnotationPresent(prop.getElement(), XmlAttribute.class) && !helper.isAnnotationPresent(prop.getElement(), XmlTransient.class) && !prop.isAnyAttribute()) { foundNonAttribute = true; } } if (foundValue && !foundNonAttribute) { return valueField; } return null; } public String getSchemaTypeNameForClassName(String className) { String typeName = Introspector.decapitalize(className.substring(className.lastIndexOf('.') + 1)); return typeName; } public void processGlobalElements(CoreProject project) { //Find any global elements for classes we've generated descriptors for, and add them as possible //root elements. if(this.globalElements == null && this.localElements == null) { return; } List<ElementDeclaration> elements = new ArrayList<ElementDeclaration>(); elements.addAll(this.localElements); elements.addAll(this.globalElements.values()); for(ElementDeclaration nextElement:elements) { QName next = nextElement.getElementName(); String nextClassName = nextElement.getJavaTypeName(); TypeInfo type = this.typeInfo.get(nextClassName); if(helper.isBuiltInJavaType(nextElement.getJavaType()) || (type !=null && type.isEnumerationType())){ //generate a class/descriptor for this element String attributeTypeName = nextClassName; if(nextElement.getJavaType().isPrimitive()) { attributeTypeName = helper.getClassForJavaClass(nextElement.getJavaType()).getName(); } if (nextElement.getAdaptedJavaTypeName() != null) { attributeTypeName = nextElement.getAdaptedJavaTypeName(); } if(next == null){ if(isBinaryData(nextElement.getJavaType())){ Class generatedClass = addByteArrayWrapperAndDescriptor(type, nextElement.getJavaType().getRawName(), nextElement,nextClassName, attributeTypeName); this.qNamesToGeneratedClasses.put(next, generatedClass); if(nextElement.getTypeMappingInfo() != null) { typeMappingInfoToGeneratedClasses.put(nextElement.getTypeMappingInfo(), generatedClass); } try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(nextClassName, false, helper.getClassLoader()); this.qNamesToDeclaredClasses.put(next, declaredClass); }catch(Exception e){ } } if(nextElement.getJavaType().isEnum()) { if(!(helper.getClassLoader() instanceof DynamicClassLoader)) { // Only generate enum wrappers in non-dynamic case. Class generatedClass = addEnumerationWrapperAndDescriptor(type, nextElement.getJavaType().getRawName(), nextElement, nextClassName, attributeTypeName); this.qNamesToGeneratedClasses.put(next, generatedClass); if(nextElement.getTypeMappingInfo() != null) { typeMappingInfoToGeneratedClasses.put(nextElement.getTypeMappingInfo(), generatedClass); } try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(nextClassName, false, helper.getClassLoader()); this.qNamesToDeclaredClasses.put(next, declaredClass); }catch(Exception ex) { } } } continue; } Class generatedClass = generateWrapperClassAndDescriptor(type, next, nextElement, nextClassName, attributeTypeName); this.qNamesToGeneratedClasses.put(next, generatedClass); if(type != null && type.isEnumerationType() && nextElement.isXmlRootElement()) { this.classToGeneratedClasses.put(type.getJavaClassName(), generatedClass); } try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(nextClassName, false, helper.getClassLoader()); this.qNamesToDeclaredClasses.put(next, declaredClass); }catch(Exception e){ } }else if(type != null && !type.isTransient()){ if(next.getNamespaceURI() == null || next.getNamespaceURI().equals("")) { type.getDescriptor().addRootElement(next.getLocalPart()); } else { Descriptor descriptor = type.getDescriptor(); String uri = next.getNamespaceURI(); String prefix = getPrefixForNamespace(uri, descriptor.getNamespaceResolver()); descriptor.addRootElement(getQualifiedString(prefix, next.getLocalPart())); } } } } private Class addByteArrayWrapperAndDescriptor(TypeInfo type , String javaClassName, ElementDeclaration nextElement, String nextClassName, String attributeTypeName){ Class generatedClass = classToGeneratedClasses.get(javaClassName); if(generatedClass == null){ generatedClass = generateWrapperClassAndDescriptor(type, null, nextElement, nextClassName, attributeTypeName); classToGeneratedClasses.put(javaClassName, generatedClass); } return generatedClass; } private Class addEnumerationWrapperAndDescriptor(TypeInfo type, String javaClassName, ElementDeclaration nextElement, String nextClassName, String attributeTypeName) { Class generatedClass = classToGeneratedClasses.get(javaClassName); if(generatedClass == null){ generatedClass = generateWrapperClassAndDescriptor(type, nextElement.getElementName(), nextElement, nextClassName, attributeTypeName); classToGeneratedClasses.put(javaClassName, generatedClass); } return generatedClass; } private Class generateWrapperClassAndDescriptor(TypeInfo type, QName next, ElementDeclaration nextElement, String nextClassName, String attributeTypeName){ String namespaceUri = null; if(next!= null){ //generate a class/descriptor for this element namespaceUri = next.getNamespaceURI(); if (namespaceUri == null || namespaceUri.equals(XMLProcessor.DEFAULT)) { namespaceUri = ""; } } TypeMappingInfo tmi = nextElement.getTypeMappingInfo(); Class generatedClass = null; JaxbClassLoader loader = getJaxbClassLoader(); if(tmi != null){ generatedClass = CompilerHelper.getExisitingGeneratedClass(tmi, typeMappingInfoToGeneratedClasses, typeMappingInfoToAdapterClasses, helper.getClassLoader()); if(generatedClass == null){ generatedClass = this.generateWrapperClass(loader.nextAvailableGeneratedClassName(), attributeTypeName, nextElement.isList(), next); } typeMappingInfoToGeneratedClasses.put(tmi, generatedClass); }else{ generatedClass = this.generateWrapperClass(loader.nextAvailableGeneratedClassName(), attributeTypeName, nextElement.isList(), next); } this.qNamesToGeneratedClasses.put(next, generatedClass); try{ Class declaredClass = PrivilegedAccessHelper.getClassForName(nextClassName, false, helper.getClassLoader()); this.qNamesToDeclaredClasses.put(next, declaredClass); }catch(Exception e){ } Descriptor desc = (Descriptor)project.getDescriptor(generatedClass); if(desc == null){ desc = new XMLDescriptor(); desc.setJavaClass(generatedClass); if(nextElement.isList()){ DirectCollectionMapping mapping = new XMLCompositeDirectCollectionMapping(); mapping.setAttributeName("value"); mapping.setXPath("text()"); mapping.setUsesSingleNode(true); mapping.setReuseContainer(true); if(type != null && type.isEnumerationType()){ mapping.setValueConverter(buildJAXBEnumTypeConverter(mapping, (EnumTypeInfo)type)); }else{ try{ Class fieldElementClass = PrivilegedAccessHelper.getClassForName(nextClassName, false, helper.getClassLoader()); mapping.setFieldElementClass(fieldElementClass); }catch(ClassNotFoundException e){ } } if(nextClassName.equals("[B") || nextClassName.equals("[Ljava.lang.Byte;")) { ((Field)mapping.getField()).setSchemaType(Constants.BASE_64_BINARY_QNAME); } else if(nextClassName.equals("javax.xml.namespace.QName")){ ((Field)mapping.getField()).setSchemaType(Constants.QNAME_QNAME); } desc.addMapping((CoreMapping)mapping); } else{ if(nextElement.getJavaTypeName().equals(OBJECT_CLASS_NAME)){ CompositeObjectMapping mapping = new XMLCompositeObjectMapping(); mapping.setAttributeName("value"); mapping.setSetMethodName("setValue"); mapping.setGetMethodName("getValue"); mapping.setKeepAsElementPolicy(UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT); mapping.setXPath("."); setTypedTextField((Field)mapping.getField()); desc.addMapping((CoreMapping)mapping); }else if(isBinaryData(nextElement.getJavaType())){ BinaryDataMapping mapping = new XMLBinaryDataMapping(); mapping.setAttributeName("value"); mapping.setXPath("."); ((Field)mapping.getField()).setSchemaType(Constants.BASE_64_BINARY_QNAME); mapping.setSetMethodName("setValue"); mapping.setGetMethodName("getValue"); mapping.getNullPolicy().setNullRepresentedByXsiNil(true); mapping.getNullPolicy().setNullRepresentedByEmptyNode(false); Class attributeClassification = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(attributeTypeName, helper.getClassLoader()); mapping.setAttributeClassification(attributeClassification); mapping.setShouldInlineBinaryData(false); //if(nextElement.getTypeMappingInfo() != null) { mapping.setSwaRef(nextElement.isXmlAttachmentRef()); mapping.setMimeType(nextElement.getXmlMimeType()); desc.addMapping((CoreMapping)mapping); }else{ DirectMapping mapping = new XMLDirectMapping(); mapping.setNullValueMarshalled(true); mapping.setAttributeName("value"); mapping.setXPath("text()"); mapping.setSetMethodName("setValue"); mapping.setGetMethodName("getValue"); if(nextElement.getDefaultValue() != null) { mapping.setNullValue(nextElement.getDefaultValue()); mapping.getNullPolicy().setNullRepresentedByXsiNil(true); } if(helper.isBuiltInJavaType(nextElement.getJavaType())){ Class attributeClassification = null; if(nextElement.getJavaType().isPrimitive()) { attributeClassification = XMLConversionManager.getDefaultManager().convertClassNameToClass(attributeTypeName); } else { attributeClassification = org.eclipse.persistence.internal.helper.Helper.getClassFromClasseName(attributeTypeName, helper.getClassLoader()); } mapping.setAttributeClassification(attributeClassification); } IsSetNullPolicy nullPolicy = new IsSetNullPolicy("isSetValue", false, true, XMLNullRepresentationType.ABSENT_NODE); //nullPolicy.setNullRepresentedByEmptyNode(true); mapping.setNullPolicy(nullPolicy); if(type != null && type.isEnumerationType()){ mapping.setConverter(buildJAXBEnumTypeConverter(mapping, (EnumTypeInfo)type)); } if(nextClassName.equals("[B") || nextClassName.equals("[Ljava.lang.Byte;")) { ((Field)mapping.getField()).setSchemaType(Constants.BASE_64_BINARY_QNAME); } else if(nextClassName.equals("javax.xml.namespace.QName")){ ((Field)mapping.getField()).setSchemaType(Constants.QNAME_QNAME); } if (nextElement.getJavaTypeAdapterClass() != null) { mapping.setConverter(new XMLJavaTypeConverter(nextElement.getJavaTypeAdapterClass())); } desc.addMapping((CoreMapping)mapping); } } if(next != null){ NamespaceInfo info = getNamespaceInfoForURI(namespaceUri); if(info != null) { NamespaceResolver resolver = info.getNamespaceResolverForDescriptor(); String prefix = null; if(namespaceUri != Constants.EMPTY_STRING){ prefix = resolver.resolveNamespaceURI(namespaceUri); if(prefix == null){ prefix = getPrefixForNamespace(namespaceUri, resolver); } } desc.setNamespaceResolver(resolver); if(nextElement.isXmlRootElement()) { desc.setDefaultRootElement(getQualifiedString(prefix, next.getLocalPart())); } else { desc.setDefaultRootElement(""); desc.addRootElement(getQualifiedString(prefix, next.getLocalPart())); desc.setResultAlwaysXMLRoot(true); } } else { if(namespaceUri.equals("")) { desc.setDefaultRootElement(next.getLocalPart()); } else { NamespaceResolver resolver = new org.eclipse.persistence.oxm.NamespaceResolver(); String prefix = getPrefixForNamespace(namespaceUri, resolver); desc.setNamespaceResolver(resolver); if(nextElement.isXmlRootElement()) { desc.setDefaultRootElement(getQualifiedString(prefix, next.getLocalPart())); } else { desc.setDefaultRootElement(""); desc.addRootElement(getQualifiedString(prefix, next.getLocalPart())); desc.setResultAlwaysXMLRoot(true); } } } } project.addDescriptor((CoreDescriptor)desc); } return generatedClass; } private String getQualifiedString(String prefix, String localPart){ if(prefix == null){ return localPart; } return prefix + Constants.COLON + localPart; } private NamespaceInfo getNamespaceInfoForURI(String namespaceUri) { Iterator<PackageInfo> namespaces = this.packageToPackageInfoMappings.values().iterator(); while(namespaces.hasNext()) { NamespaceInfo next = namespaces.next().getNamespaceInfo(); if(next.getNamespace().equals(namespaceUri)) { return next; } } return null; } @SuppressWarnings("unused") private String getPackageNameForURI(String namespaceUri) { for(String next:this.packageToPackageInfoMappings.keySet()) { if(packageToPackageInfoMappings.get(next).getNamespace().equals(namespaceUri)) { return next; } } return null; } public Class generateWrapperClass(String className, String attributeType, boolean isList, QName theQName) { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); String sig = null; cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, className.replace(".", "/"), sig, Type.getType(WrappedValue.class).getInternalName(), null); String fieldType = null; if(isList){ fieldType ="Ljava/util/List;"; }else{ fieldType = attributeType.replace(".", "/"); if(!(fieldType.startsWith("["))) { fieldType = "L" + fieldType + ";"; } } if(theQName == null){ theQName = RESERVED_QNAME; } MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitTypeInsn(Opcodes.NEW, "javax/xml/namespace/QName"); mv.visitInsn(Opcodes.DUP); mv.visitLdcInsn(theQName.getNamespaceURI()); mv.visitLdcInsn(theQName.getLocalPart()); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "javax/xml/namespace/QName", "<init>", "(Ljava/lang/String;Ljava/lang/String;)V"); mv.visitLdcInsn(Type.getType(fieldType)); mv.visitInsn(Opcodes.ACONST_NULL); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/eclipse/persistence/internal/jaxb/WrappedValue", "<init>", "(Ljavax/xml/namespace/QName;Ljava/lang/Class;Ljava/lang/Object;)V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(5, 1); mv.visitEnd(); cw.visitEnd(); byte[] classBytes = cw.toByteArray(); //byte[] classBytes = new byte[]{}; Class generatedClass = getJaxbClassLoader().generateClass(className, classBytes); return generatedClass; } public HashMap<QName, Class> getQNamesToGeneratedClasses() { return qNamesToGeneratedClasses; } public HashMap<String, Class> getClassToGeneratedClasses() { return classToGeneratedClasses; } public HashMap<QName, Class> getQNamesToDeclaredClasses() { return qNamesToDeclaredClasses; } private Map<MapEntryGeneratedKey, Class> getGeneratedMapEntryClasses() { if(generatedMapEntryClasses == null){ generatedMapEntryClasses = new HashMap<MapEntryGeneratedKey, Class>(); } return generatedMapEntryClasses; } private class MapEntryGeneratedKey { @SuppressWarnings("unused") String keyClassName; @SuppressWarnings("unused") String valueClassName; public MapEntryGeneratedKey(String keyClass, String valueClass){ keyClassName = keyClass; valueClassName = valueClass; } } private AbstractNullPolicy getWrapperNullPolicyFromProperty(Property property) { NullPolicy nullPolicy = null; if (property.isSetXmlElementWrapper()) { nullPolicy = new NullPolicy(); nullPolicy.setNullRepresentedByEmptyNode(false); nullPolicy.setSetPerformedForAbsentNode(false); if (property.getXmlElementWrapper().isNillable()) { nullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.XSI_NIL); nullPolicy.setNullRepresentedByXsiNil(true); } else { nullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.ABSENT_NODE); nullPolicy.setNullRepresentedByXsiNil(false); } } return nullPolicy; } /** * Convenience method which returns an AbstractNullPolicy built from an XmlAbstractNullPolicy. * * @param property * @param nsr if 'NullRepresentedByXsiNil' is true, this is the resolver * that we will add the schema instance prefix/uri pair to * @return * @see org.eclipse.persistence.oxm.mappings.nullpolicy.AbstractNullPolicy * @see org.eclipse.persistence.jaxb.xmlmodel.XmlAbstractNullPolicy */ private AbstractNullPolicy getNullPolicyFromProperty(Property property, NamespaceResolver nsr) { AbstractNullPolicy absNullPolicy = null; XmlAbstractNullPolicy xmlAbsNullPolicy = property.getNullPolicy(); // policy is assumed to be one of XmlNullPolicy or XmlIsSetNullPolicy if (xmlAbsNullPolicy instanceof XmlNullPolicy) { XmlNullPolicy xmlNullPolicy = (XmlNullPolicy) xmlAbsNullPolicy; NullPolicy nullPolicy = new NullPolicy(); nullPolicy.setSetPerformedForAbsentNode(xmlNullPolicy.isIsSetPerformedForAbsentNode()); absNullPolicy = nullPolicy; } else { XmlIsSetNullPolicy xmlIsSetNullPolicy = (XmlIsSetNullPolicy) xmlAbsNullPolicy; IsSetNullPolicy isSetNullPolicy = new IsSetNullPolicy(); isSetNullPolicy.setIsSetMethodName(xmlIsSetNullPolicy.getIsSetMethodName()); // handle isSetParams ArrayList<Object> parameters = new ArrayList<Object>(); ArrayList<Class> parameterTypes = new ArrayList<Class>(); List<XmlIsSetNullPolicy.IsSetParameter> params = xmlIsSetNullPolicy.getIsSetParameter(); for (XmlIsSetNullPolicy.IsSetParameter param : params) { String valueStr = param.getValue(); String typeStr = param.getType(); // create a conversion manager instance with the helper's loader XMLConversionManager mgr = new XMLConversionManager(); mgr.setLoader(helper.getClassLoader()); // handle parameter type Class typeClass = mgr.convertClassNameToClass(typeStr); // handle parameter value Object parameterValue = mgr.convertObject(valueStr, typeClass); parameters.add(parameterValue); parameterTypes.add(typeClass); } isSetNullPolicy.setIsSetParameters(parameters.toArray()); isSetNullPolicy.setIsSetParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); absNullPolicy = isSetNullPolicy; } // handle commmon settings absNullPolicy.setMarshalNullRepresentation(XMLNullRepresentationType.valueOf(xmlAbsNullPolicy.getNullRepresentationForXml().name())); absNullPolicy.setNullRepresentedByEmptyNode(xmlAbsNullPolicy.isEmptyNodeRepresentsNull()); boolean xsiRepresentsNull = xmlAbsNullPolicy.isXsiNilRepresentsNull(); if (xsiRepresentsNull) { absNullPolicy.setNullRepresentedByXsiNil(true); } return absNullPolicy; } /** * Return the base component type for a class. For example, the base * component type for Integer, Integer[], and Integer[][] are all Integer. */ private JavaClass getBaseComponentType(JavaClass javaClass) { JavaClass componentType = javaClass.getComponentType(); if(null == componentType) { return javaClass; } if(!componentType.isArray()) { return componentType; } return getBaseComponentType(componentType); } public JaxbClassLoader getJaxbClassLoader() { if (helper.getClassLoader() instanceof DynamicClassLoader) { return (JaxbClassLoader) helper.getClassLoader().getParent(); } else { return (JaxbClassLoader) helper.getClassLoader(); } } private boolean isBinaryData(JavaClass type){ return areEquals(type, CoreClassConstants.APBYTE) ||areEquals(type, "javax.activation.DataHandler") || areEquals(type, "java.awt.Image") || areEquals(type, "javax.xml.transform.Source") || areEquals(type, "javax.mail.internet.MimeMultipart"); } /** * <p>An InstantiationPolicy that does not construct any objects (and therefore * will not throw validation errors caused by a lack of a no-arg constructor).</p> * * <p>This is used by @XmlLocation, where we want to have a real mapping created * (so we can later set its value through the mapping), but where we will never * instantiate a Locator from XML (the Locator will be built internally during parsing).</p> * * @see org.eclipse.persistence.internal.descriptors.InstantiationPolicy * @see org.xml.sax.Locator */ private class NullInstantiationPolicy extends InstantiationPolicy { /** * Returns a new instance of this InstantiationPolicy's Descriptor's class. * * In this case, do nothing and return null. */ @Override public Object buildNewInstance() throws DescriptorException { return null; } } private void initializeXMLContainerMapping(XMLContainerMapping xmlContainerMapping, boolean isArray) { xmlContainerMapping.setReuseContainer(!isArray); xmlContainerMapping.setDefaultEmptyContainer(false); } private void initializeXMLMapping(XMLMapping mapping, Property property){ mapping.setAttributeName(property.getPropertyName()); // handle read-only set via metadata if (property.isSetReadOnly()) { mapping.setIsReadOnly(property.isReadOnly()); } // handle write-only set via metadata if (property.isSetWriteOnly()) { mapping.setIsWriteOnly(property.isWriteOnly()); } if (property.isMethodProperty()) { if (property.getGetMethodName() == null) { // handle case of set with no get method String paramTypeAsString = property.getType().getName(); mapping.setAttributeAccessor(new JAXBSetMethodAttributeAccessor(paramTypeAsString, helper.getClassLoader())); mapping.setIsReadOnly(true); mapping.setSetMethodName(property.getSetMethodName()); } else if (property.getSetMethodName() == null) { mapping.setGetMethodName(property.getGetMethodName()); mapping.setIsWriteOnly(true); } else { mapping.setSetMethodName(property.getSetMethodName()); mapping.setGetMethodName(property.getGetMethodName()); } } } private JavaClass containerClassImpl(JavaClass collectionType) { if (areEquals(collectionType, List.class) || areEquals(collectionType, Collection.class) || collectionType.isArray() || helper.isMapType(collectionType) ) { return jotArrayList; } else if (areEquals(collectionType, Set.class)) { return jotHashSet; } else if (areEquals(collectionType, Deque.class) || areEquals(collectionType, Queue.class)) { return jotLinkedList; } else if (areEquals(collectionType, NavigableSet.class) || areEquals(collectionType, SortedSet.class)) { return jotTreeSet; } else { return collectionType; } } }
package seedu.emeraldo.model.task; import seedu.emeraldo.commons.exceptions.IllegalValueException; import java.time.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a Task's date and time in Emeraldo. * Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)} */ public class DateTime { public static final String MESSAGE_DATETIME_CONSTRAINTS = "Task date and time must follow this format DD/MM/YYYY HH:MM in 24 hours format"; public static final Pattern DATETIME_VALIDATION_REGEX = Pattern.compile("((?<day>(0?[1-9]|[12][0-9]|3[01]))" //Day regex + "/(?<month>(0?[1-9]|[1][0-2]))/" //Month regex + "(?<year>(([0-9][0-9])?[0-9][0-9])))" //Year regex + "( (?<hour>([01][0-9]|[2][0-3])))?" //Hour regex + "(:(?<minute>([0-5][0-9])))?"); //Minute regex public final String value; public final LocalDate valueDate; public final LocalTime valueTime; public DateTime(String dateTime) throws IllegalValueException { assert dateTime != null; final Matcher matcher = DATETIME_VALIDATION_REGEX.matcher(dateTime.trim()); if (!matcher.matches()) { throw new IllegalValueException(MESSAGE_DATETIME_CONSTRAINTS); } final String day = matcher.group("day"); final String month = matcher.group("month"); final String year = matcher.group("year"); final String hour = matcher.group("hour"); final String minute = matcher.group("minute"); if(dateTime.equals("")){ //Constructing an empty DateTime object this.valueDate = null; this.valueTime = null; this.value = ""; }else if(!dateTime.contains(":")){ //Constructing a DateTime object with Date only int yearParsed = Integer.parseInt(year); int monthParsed = Integer.parseInt(month); int dayParsed = Integer.parseInt(day); this.valueDate = LocalDate.of(yearParsed, monthParsed, dayParsed); this.valueTime = null; // this.value = day + " " + returnMonthInWords(monthParsed) + " " + year; this.value = dateTime; } else { //Constructing a DateTime object with Date and time int yearParsed = Integer.parseInt(year); int monthParsed = Integer.parseInt(month); int dayParsed = Integer.parseInt(day); this.valueDate = LocalDate.of(yearParsed, monthParsed, dayParsed); int hourParsed = Integer.parseInt(hour); int minuteParsed = Integer.parseInt(minute); this.valueTime = LocalTime.of(hourParsed, minuteParsed); /* this.value = day + " " + returnMonthInWords(monthParsed) + " " + year + " " + hour + ":" + minute; */ this.value = dateTime; } } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DateTime // instanceof handles nulls && this.value.equals(((DateTime) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } private String returnMonthInWords(int monthParsed){ String monthInWords; switch(monthParsed){ case 1: monthInWords = "Jan"; break; case 2: monthInWords = "Feb"; break; case 3: monthInWords = "Mar"; break; case 4: monthInWords = "Apr"; break; case 5: monthInWords = "May"; break; case 6: monthInWords = "Jun"; break; case 7: monthInWords = "Jul"; break; case 8: monthInWords = "Aug"; break; case 9: monthInWords = "Sep"; break; case 10: monthInWords = "Oct"; break; case 11: monthInWords = "Nov"; break; case 12: monthInWords = "Dec"; break; default: monthInWords = "Invalid month"; } return monthInWords; } }
package edu.wustl.catissuecore.bizlogic; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import edu.wustl.catissuecore.domain.ClinicalDiagnosis; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.CollectionProtocolEvent; import edu.wustl.catissuecore.domain.ConsentTier; import edu.wustl.catissuecore.domain.SpecimenRequirement; import edu.wustl.catissuecore.domain.User; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.util.global.CommonServiceLocator; import edu.wustl.common.util.logger.Logger; import edu.wustl.dao.DAO; import edu.wustl.dao.daofactory.DAOConfigFactory; import edu.wustl.dao.daofactory.IDAOFactory; import edu.wustl.dao.exception.DAOException; import edu.wustl.dao.query.generator.ColumnValueBean; /** * @author * */ public class ExportCollectionProtocolBizLogic extends CatissueDefaultBizLogic { DAO dao = null; private transient final Logger logger = Logger .getCommonLogger(ExportCollectionProtocolBizLogic.class); public StringBuffer getCPXMLFile(String title) throws BizLogicException { StringBuffer csvFile = null; final IDAOFactory daofactory = DAOConfigFactory.getInstance() .getDAOFactory(CommonServiceLocator.getInstance().getAppName()); try { dao = daofactory.getDAO(); dao.openSession(null); csvFile = getCSV(getCollectionProtocol(title)); } catch (final DAOException e) { logger.error(e.getMessage(), e); throw getBizLogicException(e, e.getErrorKeyName(), e.getMsgValues()); } finally { try { if (dao != null) dao.closeSession(); } catch (final DAOException e) { logger.error(e.getMessage(), e); throw getBizLogicException(e, e.getErrorKeyName(), e .getMsgValues()); } } return csvFile; } /** * @param collectionProtocol * @return * @throws BizLogicException * @throws DAOException */ private CollectionProtocol getCollectionProtocol(String title) throws DAOException { CollectionProtocol collectionProtocol; ColumnValueBean columnValueBean = new ColumnValueBean("title", title); List<CollectionProtocol> collectionProtocols = (List<CollectionProtocol>) dao .retrieve(CollectionProtocol.class.getName(), columnValueBean); collectionProtocol = collectionProtocols.get(0); return collectionProtocol; } private StringBuffer getCSV(CollectionProtocol collectionProtocol) throws BizLogicException { StringBuffer headerString=new StringBuffer(); StringBuffer valueString=new StringBuffer(); headerString.append("Principal Investigator").append(","); valueString.append("\"").append( collectionProtocol.getPrincipalInvestigator().getLoginName()).append("\"").append(","); //headerDataMap.put("Principal Investigator", collectionProtocol.getPrincipalInvestigator().getLoginName()); Collection<User> coordinatorUsers=collectionProtocol.getCoordinatorCollection(); int coordinatorCount=1; for (User user : coordinatorUsers) { headerString.append("Principal cordinator#").append(coordinatorCount++).append(","); valueString.append("\"").append(user.getLoginName()).append("\"").append(","); } //headerDataMap.put("Title",collectionProtocol.getTitle()); headerString.append("Title").append(","); valueString.append("\"").append(collectionProtocol.getTitle()).append("\"").append(","); //headerDataMap.put("STitle",collectionProtocol.getShortTitle()); headerString.append("Short Title").append(","); valueString.append("\"").append(collectionProtocol.getShortTitle()).append("\"").append(","); if(collectionProtocol.getIrbIdentifier()!=null) { //headerDataMap.put("IRB",collectionProtocol.getIrbIdentifier()); headerString.append("IRB").append(","); valueString.append("\"").append(collectionProtocol.getIrbIdentifier()).append("\"").append(","); } //headerDataMap.put("Date",getDateAsString(collectionProtocol.getStartDate())); headerString.append("Date").append(","); valueString.append("\"").append(getDateAsString(collectionProtocol.getStartDate())).append("\"").append(","); //headerDataMap.put("URL",collectionProtocol.getDescriptionURL()); headerString.append("URL").append(","); valueString.append("\"").append(collectionProtocol.getDescriptionURL()).append("\"").append(","); //headerDataMap.put("Activity Status",collectionProtocol.getActivityStatus()); headerString.append("Activity Status").append(","); valueString.append("\"").append(collectionProtocol.getActivityStatus()).append("\"").append(","); if(collectionProtocol.getConsentsWaived()!=null) { //headerDataMap.put("Waived",collectionProtocol.getConsentsWaived().toString()); headerString.append("Waived").append(","); valueString.append("\"").append(collectionProtocol.getConsentsWaived().toString()).append("\"").append(","); } //headerDataMap.put("Aliquot In Same Container",collectionProtocol.getAliquotInSameContainer().toString()); headerString.append("Aliquot In Same Container").append(","); valueString.append("\"").append(collectionProtocol.getAliquotInSameContainer().toString()).append("\"").append(","); if(collectionProtocol.getEnrollment()!=null) { //headerDataMap.put("Enrollment",collectionProtocol.getEnrollment().toString()); headerString.append("Enrollment").append(","); valueString.append("\"").append(collectionProtocol.getEnrollment().toString()).append("\"").append(","); } Collection<ConsentTier> consentTiers=collectionProtocol.getConsentTierCollection(); int consentTiersCount=1; for (ConsentTier consentTier : consentTiers) { //headerDataMap.put("Statements#"+consentTiersCount++,consentTier.getStatement()); headerString.append("Statements#").append(consentTiersCount++).append(","); valueString.append("\"").append(consentTier.getStatement()).append("\"").append(","); } Collection<ClinicalDiagnosis> clinicalDiagnosis=collectionProtocol.getClinicalDiagnosisCollection(); int clinicalDiagnosisCount=1; for (ClinicalDiagnosis cd : clinicalDiagnosis) { //headerDataMap.put("Clinical Diagnosis#"+clinicalDiagnosisCount++,cd.getName()); headerString.append("Clinical Diagnosis#").append(clinicalDiagnosisCount++).append(","); valueString.append("\"").append(cd.getName()).append("\"").append(","); } Collection<CollectionProtocolEvent> events=collectionProtocol.getCollectionProtocolEventCollection(); int eventsCount=1; for (CollectionProtocolEvent collectionProtocolEvent : events) { //headerDataMap.put("Study Calender Event Point#"+eventsCount,collectionProtocolEvent.getStudyCalendarEventPoint().toString()); headerString.append("Study Calender Event Point#").append(eventsCount).append(","); valueString.append("\"").append(collectionProtocolEvent.getStudyCalendarEventPoint().toString()).append("\"").append(","); //headerDataMap.put("CPL#"+eventsCount,collectionProtocolEvent.getCollectionPointLabel()); headerString.append("Collection Point Label#").append(eventsCount).append(","); valueString.append("\"").append(collectionProtocolEvent.getCollectionPointLabel()).append("\"").append(","); //headerDataMap.put("CS#"+eventsCount,collectionProtocolEvent.getClinicalStatus()); headerString.append("Clinical Status#").append(eventsCount).append(","); valueString.append("\"").append(collectionProtocolEvent.getClinicalStatus()).append("\"").append(","); //headerDataMap.put("ActivityStatus#"+eventsCount,collectionProtocolEvent.getActivityStatus()); headerString.append("ActivityStatus#").append(eventsCount).append(","); valueString.append("\"").append(collectionProtocolEvent.getActivityStatus()).append("\"").append(","); Collection<SpecimenRequirement> requirements=collectionProtocolEvent.getSpecimenRequirementCollection(); int specimenRequirementCount=1; for (SpecimenRequirement specimenRequirement : requirements) { if(specimenRequirement.getParentSpecimen()==null) { //headerDataMap.put("Specimen Class"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenClass()); headerString.append("Specimen Class#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getSpecimenClass()).append("\"").append(","); //headerDataMap.put("Specimen Type"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenType()); headerString.append("Specimen Type#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getSpecimenType()).append("\"").append(","); //headerDataMap.put("Storage Location"+postfix+"#"+childSpecimenCount,((SpecimenRequirement)abstractSpecimen).getStorageType()); headerString.append("Storage Location#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getStorageType()).append("\"").append(","); //headerDataMap.put("Pathological Status"+postfix+"#"+childSpecimenCount,abstractSpecimen.getPathologicalStatus()); headerString.append("Pathological Status#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getPathologicalStatus()).append("\"").append(","); //headerDataMap.put("Initial Quantity"+postfix+"#"+childSpecimenCount,abstractSpecimen.getInitialQuantity().toString()); headerString.append("Initial Quantity#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getInitialQuantity().toString()).append("\"").append(","); //headerDataMap.put("lineage"+postfix+"#"+childSpecimenCount,abstractSpecimen.getLineage()); headerString.append("Lineage#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getLineage()).append("\"").append(","); //headerDataMap.put("Tissue Site"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenCharacteristics().getTissueSite()); headerString.append("Tissue Site#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getSpecimenCharacteristics().getTissueSite()).append("\"").append(","); //headerDataMap.put("Tissue Side"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenCharacteristics().getTissueSide()); headerString.append("Tissue Side#").append(eventsCount).append("#").append(specimenRequirementCount).append(","); valueString.append("\"").append(specimenRequirement.getSpecimenCharacteristics().getTissueSide()).append("\"").append(","); updateMapForChildSpecimen(headerString,valueString,specimenRequirement.getChildSpecimenCollection(),"#"+eventsCount+"#"+specimenRequirementCount); specimenRequirementCount++; } } eventsCount++; } headerString=headerString.replace(headerString.lastIndexOf(","), headerString.lastIndexOf(",")+1, ""); valueString=valueString.replace(valueString.lastIndexOf(","), valueString.lastIndexOf(",")+1, ""); return headerString.append("\n").append(valueString);//writeCSVFile(collectionProtocol.getShortTitle(),headerString,valueString); } private String getDateAsString(Date date) { DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); String dateString = formatter.format(date); return dateString; } private void updateMapForChildSpecimen(StringBuffer headerString,StringBuffer valueString,Collection specimenCollection,String postfix) { int childSpecimenCount=1; for (Object abstractSpecimen : specimenCollection) { //headerDataMap.put("Specimen Class"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenClass()); headerString.append("Specimen Class").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getSpecimenClass()).append("\"").append(","); //headerDataMap.put("Specimen Type"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenType()); headerString.append("Specimen Type").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getSpecimenType()).append("\"").append(","); //headerDataMap.put("Storage Location"+postfix+"#"+childSpecimenCount,((SpecimenRequirement)abstractSpecimen).getStorageType()); headerString.append("Storage Location").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getStorageType()).append("\"").append(","); //headerDataMap.put("Pathological Status"+postfix+"#"+childSpecimenCount,abstractSpecimen.getPathologicalStatus()); headerString.append("Pathological Status").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getPathologicalStatus()).append("\"").append(","); //headerDataMap.put("Initial Quantity"+postfix+"#"+childSpecimenCount,abstractSpecimen.getInitialQuantity().toString()); headerString.append("Initial Quantity").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getInitialQuantity().toString()).append("\"").append(","); //headerDataMap.put("lineage"+postfix+"#"+childSpecimenCount,abstractSpecimen.getLineage()); headerString.append("Lineage").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getLineage()).append("\"").append(","); //headerDataMap.put("Tissue Site"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenCharacteristics().getTissueSite()); headerString.append("Tissue Site").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getSpecimenCharacteristics().getTissueSite()).append("\"").append(","); //headerDataMap.put("Tissue Side"+postfix+"#"+childSpecimenCount,abstractSpecimen.getSpecimenCharacteristics().getTissueSide()); headerString.append("Tissue Side").append(postfix).append("#").append(childSpecimenCount).append(","); valueString.append("\"").append(((SpecimenRequirement)abstractSpecimen).getSpecimenCharacteristics().getTissueSide()).append("\"").append(","); updateMapForChildSpecimen(headerString,valueString,((SpecimenRequirement)abstractSpecimen).getChildSpecimenCollection(),postfix+"#"+childSpecimenCount); childSpecimenCount++; } } }
package name.abuchen.portfolio.online.impl; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; import org.junit.Test; import name.abuchen.portfolio.model.Exchange; import name.abuchen.portfolio.model.LatestSecurityPrice; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.model.SecurityPrice; import name.abuchen.portfolio.money.Values; @SuppressWarnings("nls") public class YahooFinanceQuoteFeedTest { @Test public void testCalculateDate() throws IOException { YahooFinanceQuoteFeed feed = new YahooFinanceQuoteFeed(); Security security = new Security(); security.setName("Daimler AG"); security.setIsin("DE0007100000"); security.setTickerSymbol("DAI.DE"); LocalDate nineteenHundred = LocalDate.of(1900, 1, 1); LocalDate date = feed.caculateStart(security); assertThat(date, equalTo(nineteenHundred)); security.addPrice(new SecurityPrice(LocalDate.now(), 100)); date = feed.caculateStart(security); assertThat(date, equalTo(LocalDate.now())); } @Test public void testParsingLatestQuotes() throws IOException { YahooFinanceQuoteFeed feed = new YahooFinanceQuoteFeed() { @Override protected InputStream openStream(String url) throws IOException { return getClass().getResourceAsStream("response_yahoo_quotes.txt"); } }; List<Security> securities = new ArrayList<Security>(); securities.add(new Security("Daimler AG", "DE0007100000", "DAI.DE", YahooFinanceQuoteFeed.ID)); securities.add(new Security("Adidas", "DE000A1EWWW0", "ADS.DE", YahooFinanceQuoteFeed.ID)); securities.add(new Security("Daimler AG", "DE0007100000", "BAYN.DE", YahooFinanceQuoteFeed.ID)); securities.add(new Security("Daimler AG", "DE0007100000", "BMW.DE", YahooFinanceQuoteFeed.ID)); securities.add(new Security("Daimler AG", "DE0007100000", "CBK.DE", YahooFinanceQuoteFeed.ID)); List<Exception> errors = new ArrayList<Exception>(); feed.updateLatestQuotes(securities, errors); assertThat(errors.size(), is(0)); LatestSecurityPrice latest = securities.get(0).getLatest(); assertThat(latest.getValue(), is(Values.Quote.factorize(13.71))); assertThat(latest.getTime(), equalTo(LocalDate.of(2011, Month.SEPTEMBER, 29))); assertThat(latest.getHigh(), is(Values.Quote.factorize(13.75))); assertThat(latest.getLow(), is(Values.Quote.factorize(13.70))); assertThat(latest.getVolume(), is(10037)); assertThat(latest.getPreviousClose(), is(Values.Quote.factorize(12.71))); latest = securities.get(1).getLatest(); assertThat(latest.getHigh(), is(-1L)); assertThat(latest.getLow(), is(-1L)); assertThat(latest.getVolume(), is(-1)); latest = securities.get(3).getLatest(); assertThat(latest.getTime(), equalTo(LocalDate.now())); } @Test public void testForMissingQuotesFromYahoo() throws IOException { YahooFinanceQuoteFeed feed = new YahooFinanceQuoteFeed() { @Override protected InputStream openStream(String url) throws IOException { return new ByteArrayInputStream("\"ADS.DE\",49.20,\"9/1/2011\",N/A,N/A,48.66,N/A" .getBytes(StandardCharsets.UTF_8)); } }; Security daimler = new Security("Daimler AG", "DE0007100000", "DAI.DE", YahooFinanceQuoteFeed.ID); Security adidas = new Security("Adidas", "DE000A1EWWW0", "ADS.DE", YahooFinanceQuoteFeed.ID); List<Security> securities = new ArrayList<Security>(); securities.add(daimler); securities.add(adidas); List<Exception> errors = new ArrayList<Exception>(); feed.updateLatestQuotes(securities, errors); // not first, but second security must have value LatestSecurityPrice latest = adidas.getLatest(); assertThat(latest.getValue(), is(Values.Quote.factorize(49.20))); assertThat(errors.size(), is(1)); assertThat(errors.get(0).getMessage(), containsString(daimler.getTickerSymbol())); } @Test public void testParsingHistoricalQuotes() throws IOException { YahooFinanceQuoteFeed feed = new YahooFinanceQuoteFeed() { @Override protected InputStream openStream(String wknUrl) throws IOException { return getClass().getResourceAsStream("response_yahoo_historical.txt"); } }; Security security = new Security(); security.setTickerSymbol("DAI.DE"); feed.updateHistoricalQuotes(security, new ArrayList<Exception>()); assertThat(security.getPrices().size(), is(2257)); assertThat(security.getPrices().get(0), equalTo(new SecurityPrice(LocalDate.of(2003, Month.JANUARY, 1), Values.Quote.factorize(29.35)))); assertThat(security.getPrices().get(security.getPrices().size() - 1), equalTo( new SecurityPrice(LocalDate.of(2011, Month.SEPTEMBER, 22), Values.Quote.factorize(32.74)))); } @Test public void testParsingHistoricalAdjustedCloseQuotes() throws IOException { YahooFinanceAdjustedCloseQuoteFeed feed = new YahooFinanceAdjustedCloseQuoteFeed() { @Override protected InputStream openStream(String wknUrl) throws IOException { return getClass().getResourceAsStream("response_yahoo_historical.txt"); } }; Security security = new Security(); security.setTickerSymbol("DAI.DE"); feed.updateHistoricalQuotes(security, new ArrayList<Exception>()); assertThat(security.getPrices().size(), is(2257)); assertThat(security.getPrices().get(0), equalTo(new SecurityPrice(LocalDate.of(2003, Month.JANUARY, 1), Values.Quote.factorize(22.55)))); assertThat(security.getPrices().get(security.getPrices().size() - 1), equalTo( new SecurityPrice(LocalDate.of(2011, Month.SEPTEMBER, 22), Values.Quote.factorize(32.74)))); } @Test public void testThatAtLeastTheGivenExchangeIsReturned() throws IOException { YahooFinanceQuoteFeed feed = new YahooFinanceQuoteFeed() { @Override protected void searchSymbols(List<Exchange> answer, String query) throws IOException { throw new IOException(); } }; Security s = new Security(); s.setTickerSymbol("BAS.DE"); ArrayList<Exception> errors = new ArrayList<Exception>(); List<Exchange> exchanges = feed.getExchanges(s, errors); assertThat(exchanges.size(), is(1)); assertThat(exchanges.get(0).getId(), is("BAS.DE")); assertThat(errors.size(), is(1)); } }
package seedu.jimi.logic.parser; import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.jimi.commons.core.Messages.MESSAGE_INVALID_DATE; import static seedu.jimi.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.jimi.commons.core.Config; import seedu.jimi.commons.exceptions.DateNotParsableException; import seedu.jimi.commons.exceptions.IllegalValueException; import seedu.jimi.commons.util.StringUtil; import seedu.jimi.logic.commands.AddCommand; import seedu.jimi.logic.commands.ClearCommand; import seedu.jimi.logic.commands.Command; import seedu.jimi.logic.commands.CompleteCommand; import seedu.jimi.logic.commands.DeleteCommand; import seedu.jimi.logic.commands.EditCommand; import seedu.jimi.logic.commands.ExitCommand; import seedu.jimi.logic.commands.FindCommand; import seedu.jimi.logic.commands.HelpCommand; import seedu.jimi.logic.commands.IncorrectCommand; import seedu.jimi.logic.commands.ListCommand; import seedu.jimi.logic.commands.SaveAsCommand; import seedu.jimi.logic.commands.SelectCommand; import seedu.jimi.logic.commands.ShowCommand; /** * Parses user input. */ public class JimiParser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern TAGGABLE_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<ArgsDetails>[^/]+)(?<tagArguments>(?: t/[^/]+)?)"); // zero or one tag only private static final Pattern EDIT_DATA_ARGS_FORMAT = // accepts index at beginning, follows task/event patterns after Pattern.compile("(?<targetIndex>[te]\\d+\\s)(?<editDetails>.+)"); // acccepts in the format of a deadline task or event private static final Pattern EDIT_DETAILS_FORMAT = Pattern.compile( "(\"(?<taskDetails>.+)\"\\s?)?(((due (?<deadline>.+))?)|((on (?<startDateTime>((?!to ).)*))?(to (?<endDateTime>.+))?))"); private static final Pattern ADD_TASK_DATA_ARGS_FORMAT = Pattern.compile("(\"(?<taskDetails>.+)\")( due (?<dateTime>.+))?"); private static final Pattern ADD_EVENT_DATA_ARGS_FORMAT = Pattern.compile("(\"(?<taskDetails>.+)\") on (?<startDateTime>((?! to ).)*)( to (?<endDateTime>.+))?"); private static final Pattern SHOW_COMMAND_ARGS_FORMAT = Pattern.compile("(?<sectionToShow>.+)"); private static final Pattern SAVE_DIRECTORY_ARGS_FORMAT = Pattern.compile("(?<filePath>.+).xml"); private static final Pattern SAVE_RESET_DIRECTORY_ARGS_FORMAT = Pattern.compile(SaveAsCommand.COMMAND_WORD_RESET); private static final List<Command> COMMAND_STUB_LIST = Arrays.asList( new AddCommand(), new EditCommand(), new CompleteCommand(), new SelectCommand(), new DeleteCommand(), new ClearCommand(), new FindCommand(), new ListCommand(), new ShowCommand(), new ExitCommand(), new HelpCommand(), new SaveAsCommand() ); private static final String XML_FILE_EXTENSION = ".xml"; public JimiParser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments").trim(); return prepareCommand(commandWord, arguments); } /** * Identifies which command to prepare according to raw command word. * * @param commandWord command word from raw input * @param arguments arguments from raw input * @return correct Command corresponding to the command word if valid, else returns incorrect command. */ private Command prepareCommand(String commandWord, String arguments) { for (Command command : COMMAND_STUB_LIST) { // if validation checks implemented by the respective commands are passed if (command.isValidCommandWord(commandWord)) { // identify which command this is if (command instanceof AddCommand) { return prepareAdd(arguments); } else if (command instanceof EditCommand) { return prepareEdit(arguments); } else if (command instanceof CompleteCommand) { return prepareComplete(arguments); } else if (command instanceof SelectCommand) { return prepareSelect(arguments); } else if (command instanceof DeleteCommand) { return prepareDelete(arguments); } else if (command instanceof FindCommand) { return prepareFind(arguments); } else if (command instanceof ShowCommand) { return prepareShow(arguments); } else if (command instanceof SaveAsCommand) { return prepareSaveAs(arguments); } else { // commands that do not require arguments e.g. exit return command; } } } return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args) { final Matcher detailsAndTagsMatcher = TAGGABLE_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate entire args string format if (!detailsAndTagsMatcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } final Matcher taskDetailsMatcher = ADD_TASK_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim()); final Matcher eventDetailsMatcher = ADD_EVENT_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim()); if (taskDetailsMatcher.matches()) { // if user trying to add task return generateAddCommandForTask(detailsAndTagsMatcher, taskDetailsMatcher); } else if (eventDetailsMatcher.matches()) { // if user trying to add event return generateAddCommandForEvent(detailsAndTagsMatcher, eventDetailsMatcher); } /* default return IncorrectCommand */ return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } /** * Creates an AddCommand in the context of adding an event. * * @return an AddCommand if raw args is valid, else IncorrectCommand */ private Command generateAddCommandForEvent(final Matcher detailsAndTagsMatcher, final Matcher eventDetailsMatcher) { try { List<Date> startDates = parseStringToDate(eventDetailsMatcher.group("startDateTime")); List<Date> endDates = parseStringToDate(eventDetailsMatcher.group("endDateTime")); return new AddCommand( eventDetailsMatcher.group("taskDetails"), startDates, endDates, getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")) ); } catch (DateNotParsableException e) { return new IncorrectCommand(e.getMessage()); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Creates an AddCommand in the context of adding an task. * * @return an AddCommand if raw args is valid, else IncorrectCommand */ private Command generateAddCommandForTask(final Matcher detailsAndTagsMatcher, final Matcher taskDetailsMatcher) { try { List<Date> dates = parseStringToDate(taskDetailsMatcher.group("dateTime")); return new AddCommand( taskDetailsMatcher.group("taskDetails"), dates, getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")) ); } catch (DateNotParsableException e) { return new IncorrectCommand(e.getMessage()); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } private static List<Date> parseStringToDate(final String str) throws DateNotParsableException { if (str == null) { return new ArrayList<Date>(); } final Parser dateParser = new Parser(); final List<DateGroup> groups = dateParser.parse(str); if (!groups.isEmpty()) { return groups.get(0).getDates(); } else { throw new DateNotParsableException(MESSAGE_INVALID_DATE); } } /** * Parses arguments in context of the edit task command. * * @param args Full user command input args * @return the prepared edit command */ private Command prepareEdit(String args) { final Matcher detailsAndTagsMatcher = TAGGABLE_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!detailsAndTagsMatcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } final Matcher editArgsMatcher = EDIT_DATA_ARGS_FORMAT.matcher(detailsAndTagsMatcher.group("ArgsDetails").trim()); if (!editArgsMatcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } // User wishes to remove dates if (editArgsMatcher.group("editDetails").trim().equals(EditCommand.COMMAND_REMOVE_DATES)) { return new EditCommand(editArgsMatcher.group("targetIndex")); } final Matcher editDetailsMatcher = EDIT_DETAILS_FORMAT.matcher(editArgsMatcher.group("editDetails").trim()); if (!editDetailsMatcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { return generateEditCommand(detailsAndTagsMatcher, editArgsMatcher, editDetailsMatcher); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** Generates an edit command */ private Command generateEditCommand(Matcher detailsAndTagsMatcher, Matcher editArgsMatcher, Matcher editDetailsMatcher) throws IllegalValueException { List<Date> deadline = parseStringToDate(editDetailsMatcher.group("deadline")); List<Date> eventStart = parseStringToDate(editDetailsMatcher.group("startDateTime")); List<Date> eventEnd = parseStringToDate(editDetailsMatcher.group("endDateTime")); /* validating integer index */ Optional<Integer> index = parseIndex(editArgsMatcher.group("targetIndex").substring(1)); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } return new EditCommand( editDetailsMatcher.group("taskDetails"), getTagsFromArgs(detailsAndTagsMatcher.group("tagArguments")), deadline, eventStart, eventEnd, editArgsMatcher.group("targetIndex") ); } /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the complete task command. * * @param args full command args string * @return the prepared command */ private Command prepareComplete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, CompleteCommand.MESSAGE_USAGE)); } return new CompleteCommand(index.get()); } /** * Parses arguments in the context of the delete task command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } /** * Parses arguments in the context of the select task command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if (!index.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Parses arguments to filter section of task panel to be displayed to user. * @param args full command args string * @return the prepared command */ private Command prepareShow(String args) { final Matcher matcher = SHOW_COMMAND_ARGS_FORMAT.matcher(args.trim()); boolean keywordFound = false; //goes through list of keywords to check if user input is valid for (String validKey : ShowCommand.VALID_KEYWORDS) { if (validKey.contains(args)) { keywordFound = true; break; } } if (!keywordFound || !matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ShowCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String sectionToShow = matcher.group("sectionToShow"); return new ShowCommand(sectionToShow); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find task command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } /** * Parses arguments in the context of the save as command. * * @param full command args string * @return the prepared command */ private Command prepareSaveAs(String args) { final Matcher resetMatcher = SAVE_RESET_DIRECTORY_ARGS_FORMAT.matcher(args.trim()); if (resetMatcher.matches()) { return new SaveAsCommand(Config.DEFAULT_XML_FILE_PATH); } final Matcher matcher = SAVE_DIRECTORY_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveAsCommand.MESSAGE_USAGE)); } return new SaveAsCommand(matcher.group("filePath") + XML_FILE_EXTENSION); } }
package org.navalplanner.web.orders; import static org.navalplanner.web.I18nHelper._; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.LocalDate; import org.navalplanner.business.advance.bootstrap.PredefinedAdvancedTypes; import org.navalplanner.business.advance.daos.IAdvanceAssignmentDAO; import org.navalplanner.business.advance.daos.IAdvanceMeasurementDAO; import org.navalplanner.business.advance.daos.IAdvanceTypeDAO; import org.navalplanner.business.advance.entities.AdvanceAssignment; import org.navalplanner.business.advance.entities.AdvanceMeasurement; import org.navalplanner.business.advance.entities.AdvanceMeasurementComparator; import org.navalplanner.business.advance.entities.AdvanceType; import org.navalplanner.business.advance.entities.DirectAdvanceAssignment; import org.navalplanner.business.advance.entities.IndirectAdvanceAssignment; import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException; import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.orders.daos.IOrderElementDAO; import org.navalplanner.business.orders.entities.OrderElement; import org.navalplanner.business.planner.entities.consolidations.CalculatedConsolidatedValue; import org.navalplanner.business.planner.entities.consolidations.CalculatedConsolidation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.zkoss.zul.SimpleXYModel; import org.zkoss.zul.XYModel; /** * Service to manage the advance of a selected order element * @author Susana Montes Pedreira <smontes@wirelessgalicia.com> */ @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class ManageOrderElementAdvancesModel implements IManageOrderElementAdvancesModel { private static final Log LOG = LogFactory .getLog(ManageOrderElementAdvancesModel.class); @Autowired private final IAdvanceTypeDAO advanceTypeDAO; @Autowired private final IOrderElementDAO orderElementDAO; private OrderElement orderElement; private DirectAdvanceAssignment advanceAssignment; private boolean isIndirectAdvanceAssignment = false; private List<AdvanceAssignment> listAdvanceAssignments; private List<AdvanceType> listAdvanceTypes; @Autowired public ManageOrderElementAdvancesModel( IAdvanceMeasurementDAO advanceMeasurementDAO, IAdvanceTypeDAO advanceTypeDAO, IOrderElementDAO orderElementDAO, IAdvanceAssignmentDAO advanceAssignmentDAO) { Validate.notNull(advanceMeasurementDAO); this.advanceTypeDAO = advanceTypeDAO; this.orderElementDAO = orderElementDAO; } @Override public String getInfoAdvanceAssignment(){ if (this.advanceAssignment == null || this.orderElement == null) { return ""; } return getInfoAdvanceAssignment(this.advanceAssignment); } private String getInfoAdvanceAssignment( DirectAdvanceAssignment assignment) { if (assignment == null) { return ""; } if ((assignment.getAdvanceType() == null) || assignment.getMaxValue() == null) { return ""; } return _("{0} (max: {1})", assignment.getAdvanceType() .getUnitName(), assignment.getMaxValue()); } @Override @Transactional(readOnly = true) public List<AdvanceMeasurement> getAdvanceMeasurements() { if (this.advanceAssignment == null || this.orderElement == null) { return new ArrayList<AdvanceMeasurement>(); } return new ArrayList<AdvanceMeasurement>(this.advanceAssignment .getAdvanceMeasurements()); } @Override @Transactional(readOnly = true) public List<AdvanceAssignment> getAdvanceAssignments() { if (orderElement == null) { return new ArrayList<AdvanceAssignment>(); } return listAdvanceAssignments; } @Override public void refreshChangesFromOrderElement() { List<AdvanceAssignment> listAdvanceAssignmentsCopy = new ArrayList<AdvanceAssignment>( listAdvanceAssignments); fillVariables(); for (AdvanceAssignment advance : listAdvanceAssignmentsCopy) { if ((!listAdvanceAssignments.contains(advance)) && (advance instanceof DirectAdvanceAssignment)) { listAdvanceAssignments.add(advance); } } } @Override public void prepareEditAdvanceMeasurements(AdvanceAssignment assignment) { if (assignment instanceof IndirectAdvanceAssignment) { this.advanceAssignment = orderElement .calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) assignment); this.isIndirectAdvanceAssignment = true; } else { if (assignment instanceof DirectAdvanceAssignment) { this.advanceAssignment = (DirectAdvanceAssignment) assignment; this.isIndirectAdvanceAssignment = false; } } } public void createPercentageAdvances(OrderElement orderElement) throws DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException { if (orderElement != null) { DirectAdvanceAssignment advancePercentage = orderElement .getAdvanceAssignmentByType(PredefinedAdvancedTypes.PERCENTAGE .getType()); boolean existDirectPercentageAdvance = ((advancePercentage != null) && (!advancePercentage .isFake())); if ((orderElement.isSchedulingPoint()) && (orderElement.getReportGlobalAdvanceAssignment() == null) && (!existDirectPercentageAdvance)) { createPercentageAdvance(orderElement); } else if (!existDirectPercentageAdvance) { for (OrderElement child : orderElement.getChildren()) { createPercentageAdvances(child); } } } } private void createPercentageAdvance(OrderElement orderElement) throws DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException { DirectAdvanceAssignment newAdvance = DirectAdvanceAssignment.create(); newAdvance.setOrderElement(orderElement); for (AdvanceType type : this.listAdvanceTypes) { if (type.getUnitName().equals( PredefinedAdvancedTypes.PERCENTAGE.getTypeName())) { newAdvance.setAdvanceType(type); newAdvance.setMaxValue(getMaxValue(type)); } } newAdvance.setReportGlobalAdvance(true); orderElement.addAdvanceAssignment(newAdvance); } @Override @Transactional(readOnly = true) public void initEdit(OrderElement orderElement) { this.orderElement = orderElement; this.advanceAssignment = null; if (orderElement != null){ loadAdvanceTypes(); reattachmentOrderElement(); forceLoadAdvanceAssignmentsAndMeasurements(); fillVariables(); } } private void forceLoadAdvanceAssignmentsAndMeasurements() { for (DirectAdvanceAssignment each : orderElement .getDirectAdvanceAssignments()) { forceLoadAdvanceConsolidatedValues(each); each.getNonCalculatedConsolidation().size(); each.getAdvanceType().getUnitName(); } for (IndirectAdvanceAssignment each : orderElement .getIndirectAdvanceAssignments()) { each.getCalculatedConsolidation().size(); each.getAdvanceType().getUnitName(); DirectAdvanceAssignment fakedDirect = orderElement .calculateFakeDirectAdvanceAssignment(each); if (fakedDirect != null) { forceLoadAdvanceConsolidatedValues(fakedDirect); } else { LOG .warn("Fake direct advance assignment shouldn't be NULL for type '" + each.getAdvanceType().getUnitName() + "'"); } } } private void forceLoadAdvanceConsolidatedValues( DirectAdvanceAssignment advance) { for (AdvanceMeasurement measurement : advance.getAdvanceMeasurements()) { measurement.getNonCalculatedConsolidatedValues().size(); } } public void reattachmentOrderElement() { orderElementDAO.reattach(orderElement); } private void fillVariables() { this.listAdvanceAssignments = new ArrayList<AdvanceAssignment>(); for (DirectAdvanceAssignment each : this.orderElement .getDirectAdvanceAssignments()) { this.listAdvanceAssignments.add(each); } for (IndirectAdvanceAssignment each : orderElement .getIndirectAdvanceAssignments()) { this.listAdvanceAssignments.add(each); } } @Override public boolean addNewLineAdvaceAssignment() { DirectAdvanceAssignment newAdvance = DirectAdvanceAssignment.create(); newAdvance.setOrderElement(this.orderElement); /* * set the first advance type of the list as the default */ List<AdvanceType> listAdvanceType = getPossibleAdvanceTypes(newAdvance); if (!listAdvanceType.isEmpty()) { newAdvance.setAdvanceType(listAdvanceType.get(0)); newAdvance.setMaxValue(getMaxValue(listAdvanceType.get(0))); } else { return false; } if (listAdvanceAssignments.isEmpty()) { newAdvance.setReportGlobalAdvance(true); } listAdvanceAssignments.add(newAdvance); return true; } @Override public BigDecimal getMaxValue(AdvanceType advanceType) { if (advanceType != null) { return advanceType.getDefaultMaxValue(); } return BigDecimal.ZERO; } @Override public AdvanceAssignment getSpreadAdvance() { for(AdvanceAssignment advance : getAdvanceAssignments()){ if(advance.getReportGlobalAdvance()){ return advance; } } return null; } @Override public AdvanceMeasurement addNewLineAdvaceMeasurement() { if (this.advanceAssignment != null) { AdvanceMeasurement newMeasurement = AdvanceMeasurement.create(); newMeasurement.setDate(new LocalDate()); newMeasurement.setAdvanceAssignment(this.advanceAssignment); if (!this.advanceAssignment.addAdvanceMeasurements( newMeasurement)) { newMeasurement.setDate(null); this.advanceAssignment.addAdvanceMeasurements(newMeasurement); } return newMeasurement; } return null; } @Override public void removeLineAdvanceAssignment(AdvanceAssignment advance) { this.listAdvanceAssignments.remove(advance); orderElement.removeAdvanceAssignment(advance); this.advanceAssignment = null; } @Override public void removeLineAdvanceMeasurement(AdvanceMeasurement advance) { this.advanceAssignment.removeAdvanceMeasurements(advance); } @Override public List<AdvanceType> getPossibleAdvanceTypes( DirectAdvanceAssignment directAdvanceAssignment) { if(orderElement == null){ return new ArrayList<AdvanceType>(); } List<AdvanceType> advanceTypes = new ArrayList<AdvanceType>(); for (AdvanceType advanceType : this.listAdvanceTypes) { if (advanceType.getUnitName().equals( PredefinedAdvancedTypes.CHILDREN.getTypeName())) { continue; } if (existsAdvanceTypeAlreadyInThisOrderElement(advanceType)) { if ((directAdvanceAssignment.getAdvanceType() == null) || (!directAdvanceAssignment.getAdvanceType() .getUnitName() .equals(advanceType.getUnitName()))) { continue; } } advanceTypes.add(advanceType); } return getSpecificOrder(advanceTypes); } private List<AdvanceType> getSpecificOrder(List<AdvanceType> advanceTypes ){ Collections.sort(advanceTypes, new Comparator<AdvanceType>(){ @Override public int compare(AdvanceType arg0, AdvanceType arg1) { if((arg0 == null) || (arg0.getUnitName() == null)){ return -1; } if((arg1 == null) || (arg1.getUnitName() == null) || (arg1.getUnitName().equals(PredefinedAdvancedTypes.PERCENTAGE.getTypeName()))){ return 1; } if (arg0.getUnitName().equals( PredefinedAdvancedTypes.PERCENTAGE.getTypeName())) { return -1; } return (arg0.getUnitName().compareTo(arg1.getUnitName())); } }); return advanceTypes; } private boolean existsAdvanceTypeAlreadyInThisOrderElement( AdvanceType advanceType) { if (listAdvanceAssignments != null) { for (AdvanceAssignment each : listAdvanceAssignments) { if ((each.getAdvanceType() != null) && (each.getAdvanceType().getUnitName() .equals(advanceType.getUnitName()))) { return true; } } } return false; } @Transactional(readOnly = true) private void loadAdvanceTypes() { this.listAdvanceTypes = this.advanceTypeDAO.findActivesAdvanceTypes(); } @Override public boolean isReadOnlyAdvanceMeasurements(){ if (this.advanceAssignment == null) { return true; } AdvanceType advanceType = this.advanceAssignment.getAdvanceType(); if (advanceType != null) { if (advanceType.isQualityForm()) { return true; } } return this.isIndirectAdvanceAssignment; } @Override public void cleanAdvance(DirectAdvanceAssignment advanceAssignment) { if (advanceAssignment != null) { advanceAssignment.clearAdvanceMeasurements(); } } @Override public void resetAdvanceAssignment() { this.advanceAssignment = null; } @Override @Transactional(readOnly = true) public void confirmSave() throws InstanceNotFoundException, DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException { orderElementDAO.checkVersion(orderElement); reattachmentOrderElement(); validateBasicData(); } private void validateBasicData() throws InstanceNotFoundException, DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException{ updateRemoveAdvances(); for (AdvanceAssignment each : this.listAdvanceAssignments) { if (each instanceof DirectAdvanceAssignment) { validateBasicData((DirectAdvanceAssignment) each); } } } private void updateRemoveAdvances(){ for (AdvanceAssignment each : this.listAdvanceAssignments) { AdvanceAssignment advance = yetExistAdvanceAssignment(each); if (advance == null) { removeAdvanceAssignment(each); } } } private void validateBasicData( DirectAdvanceAssignment directAdvanceAssignment) throws InstanceNotFoundException,DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException{ if (directAdvanceAssignment.getVersion() == null) { addAdvanceAssignment(directAdvanceAssignment); } } private AdvanceAssignment yetExistAdvanceAssignment( AdvanceAssignment assignment) { for (AdvanceAssignment advance : this.orderElement .getDirectAdvanceAssignments()) { if (advance.getVersion() != null && advance.getId().equals(assignment.getId())) { return advance; } } return null; } @Transactional(readOnly = true) private void addAdvanceAssignment( DirectAdvanceAssignment newAdvanceAssignment) throws DuplicateAdvanceAssignmentForOrderElementException, DuplicateValueTrueReportGlobalAdvanceException{ this.orderElement.addAdvanceAssignment(newAdvanceAssignment); } private void removeAdvanceAssignment(AdvanceAssignment assignment) { if (assignment != null) { orderElement.removeAdvanceAssignment(assignment); } } @Override public boolean isPrecisionValid(AdvanceMeasurement advanceMeasurement) { if ((this.advanceAssignment != null) && (this.advanceAssignment.getAdvanceType() != null)) { return advanceMeasurement.checkConstraintValidPrecision(); } return true; } @Override public boolean greatThanMaxValue(AdvanceMeasurement advanceMeasurement) { if (this.advanceAssignment == null || this.advanceAssignment.getMaxValue() == null) { return false; } return !(advanceMeasurement.checkConstraintValueIsLessThanMaxValue()); } @Override public boolean lessThanPreviousMeasurements() { if (this.advanceAssignment == null) { return false; } return !(this.advanceAssignment .checkConstraintValidAdvanceMeasurements()); } @Override public boolean isDistinctValidDate(LocalDate value, AdvanceMeasurement newAdvanceMeasurement) { if (this.advanceAssignment == null) { return true; } for (AdvanceMeasurement advanceMeasurement : advanceAssignment .getAdvanceMeasurements()) { LocalDate oldDate = advanceMeasurement.getDate(); if (oldDate != null && !newAdvanceMeasurement.equals(advanceMeasurement) && oldDate.compareTo(new LocalDate(value)) == 0) { return false; } } return true; } @Override public BigDecimal getUnitPrecision(){ if (this.advanceAssignment == null) { return BigDecimal.ZERO; } return this.advanceAssignment.getAdvanceType().getUnitPrecision(); } @Override @Transactional(readOnly = true) public AdvanceMeasurement getLastAdvanceMeasurement( DirectAdvanceAssignment assignment) { if (assignment != null) { SortedSet<AdvanceMeasurement> advanceMeasurements = assignment .getAdvanceMeasurements(); if (advanceMeasurements.size() > 0) { return advanceMeasurements.first(); } } return null; } @Override public void sortListAdvanceMeasurement() { if (advanceAssignment != null) { ArrayList<AdvanceMeasurement> advanceMeasurements = new ArrayList<AdvanceMeasurement>( advanceAssignment.getAdvanceMeasurements()); Collections.sort(advanceMeasurements, new AdvanceMeasurementComparator()); TreeSet<AdvanceMeasurement> measurements = new TreeSet<AdvanceMeasurement>( new AdvanceMeasurementComparator()); measurements.addAll(advanceMeasurements); this.advanceAssignment .setAdvanceMeasurements(measurements); } } @Override public BigDecimal getPercentageAdvanceMeasurement( AdvanceMeasurement advanceMeasurement) { AdvanceAssignment assignment = advanceMeasurement .getAdvanceAssignment(); if (assignment == null) { return BigDecimal.ZERO; } BigDecimal maxValue; if (assignment instanceof IndirectAdvanceAssignment) { maxValue = orderElement.calculateFakeDirectAdvanceAssignment( (IndirectAdvanceAssignment) assignment).getMaxValue(); } else { maxValue = ((DirectAdvanceAssignment) assignment) .getMaxValue(); } if (maxValue.compareTo(BigDecimal.ZERO) <= 0) { return BigDecimal.ZERO; } BigDecimal value = advanceMeasurement.getValue(); if (value == null) { return BigDecimal.ZERO; } BigDecimal division = value.divide(maxValue.setScale(2), 4, RoundingMode.DOWN); return (division.multiply(new BigDecimal(100))).setScale(2, RoundingMode.DOWN); } @Override @Transactional(readOnly = true) public DirectAdvanceAssignment calculateFakeDirectAdvanceAssignment( IndirectAdvanceAssignment indirectAdvanceAssignment) { if ((orderElement == null) || (orderElement.isLeaf())) { return null; } reattachmentOrderElement(); return orderElement .calculateFakeDirectAdvanceAssignment(indirectAdvanceAssignment); } @Override @Transactional(readOnly = true) public BigDecimal getAdvancePercentageChildren() { if ((orderElement == null) || orderElement.isLeaf()) { return null; } reattachmentOrderElement(); return orderElement.getAdvancePercentageChildren(); } @Override @Transactional(readOnly = true) public XYModel getChartData(Set<AdvanceAssignment> selectedAdvances) { XYModel xymodel = new SimpleXYModel(); for (AdvanceAssignment each : selectedAdvances) { DirectAdvanceAssignment directAdvanceAssignment; if (each instanceof DirectAdvanceAssignment) { directAdvanceAssignment = (DirectAdvanceAssignment) each; } else { directAdvanceAssignment = calculateFakeDirectAdvanceAssignment((IndirectAdvanceAssignment) each); } String title = getInfoAdvanceAssignment(directAdvanceAssignment); SortedSet<AdvanceMeasurement> listAdvanceMeasurements = directAdvanceAssignment .getAdvanceMeasurements(); if (listAdvanceMeasurements.size() > 1) { for (AdvanceMeasurement advanceMeasurement : listAdvanceMeasurements) { BigDecimal value = advanceMeasurement.getValue(); if ((selectedAdvances.size() > 1) && (value != null)) { BigDecimal maxValue = directAdvanceAssignment .getMaxValue(); value = value.divide(maxValue, RoundingMode.DOWN); } LocalDate date = advanceMeasurement.getDate(); if ((value != null) && (date != null)) { xymodel.addValue(title, Long.valueOf(date .toDateTimeAtStartOfDay().getMillis()), value); } } } } return xymodel; } @Override @Transactional(readOnly = true) public boolean hasConsolidatedAdvances(AdvanceAssignment advance) { if (advance instanceof DirectAdvanceAssignment) { if ((advance.getReportGlobalAdvance()) && (!((DirectAdvanceAssignment) advance) .getNonCalculatedConsolidation().isEmpty())) { return true; } return ((!((DirectAdvanceAssignment) advance).isFake()) && (!canBeRemovedAllAdvanceMeasurements((DirectAdvanceAssignment) advance))); } else { return ((advance.getReportGlobalAdvance()) && (!((IndirectAdvanceAssignment) advance) .getCalculatedConsolidation().isEmpty())); } } private boolean canBeRemovedAllAdvanceMeasurements( DirectAdvanceAssignment advance) { Iterator<AdvanceMeasurement> iterator = advance .getAdvanceMeasurements().iterator(); while (iterator.hasNext()) { if (!canRemoveOrChange(iterator.next())) { return false; } } return true; } @Transactional(readOnly = true) public boolean canRemoveOrChange(AdvanceMeasurement advanceMeasurement) { return (!hasConsolidatedAdvances(advanceMeasurement)); } @Transactional(readOnly = true) public boolean hasConsolidatedAdvances(AdvanceMeasurement advanceMeasurement) { return hasConsolidatedAdvances(advanceMeasurement, isIndirectAdvanceAssignment); } private boolean hasConsolidatedAdvances( AdvanceMeasurement advanceMeasurement, boolean isIndirectAdvanceAssignment) { if (isIndirectAdvanceAssignment) { return false; } if (!advanceMeasurement.getNonCalculatedConsolidatedValues().isEmpty()) { return true; } return findIndirectConsolidation(advanceMeasurement); } @Override @Transactional(readOnly = true) public boolean isQualityForm(AdvanceAssignment advance) { AdvanceType advanceType = advance.getAdvanceType(); advanceTypeDAO.reattach(advanceType); return advanceType.isQualityForm(); } @Override @Transactional(readOnly = true) public boolean findIndirectConsolidation( AdvanceMeasurement advanceMeasurement) { AdvanceAssignment advance = advanceMeasurement.getAdvanceAssignment(); if ((orderElement != null) && (orderElement.getParent() != null) && (advance instanceof DirectAdvanceAssignment)) { List<String> types = new ArrayList<String>(); types.add(advance.getAdvanceType().getUnitName()); if (advance.getReportGlobalAdvance()) { types.add(PredefinedAdvancedTypes.CHILDREN.getTypeName()); } orderElementDAO.reattach(orderElement); Set<IndirectAdvanceAssignment> indirects = getSpreadIndirectAdvanceAssignmentWithSameType( orderElement, types); for (IndirectAdvanceAssignment indirect : indirects) { if (findConsolidatedAdvance(indirect .getCalculatedConsolidation(), advanceMeasurement)) { return true; } } } return false; } private Set<IndirectAdvanceAssignment> getSpreadIndirectAdvanceAssignmentWithSameType( OrderElement orderElement, List<String> types) { Set<IndirectAdvanceAssignment> result = new HashSet<IndirectAdvanceAssignment>(); for (IndirectAdvanceAssignment indirect : orderElement .getIndirectAdvanceAssignments()) { if ((indirect.getReportGlobalAdvance()) && (types.contains(indirect.getAdvanceType().getUnitName()))) { result.add(indirect); } } OrderElement parent = orderElement.getParent(); if (parent != null) { result.addAll(getSpreadIndirectAdvanceAssignmentWithSameType( parent, types)); } return result; } private boolean findConsolidatedAdvance( Set<CalculatedConsolidation> consolidations, AdvanceMeasurement advance) { for (CalculatedConsolidation consolidation : consolidations) { for (CalculatedConsolidatedValue value : consolidation .getCalculatedConsolidatedValues()) { if ((value.getDate() != null) && (advance.getDate() != null) && (value.getDate().compareTo(advance.getDate()) == 0)) { return true; } } } return false; } }
package org.jetel.data.parser; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.CloverDataRecordSerializer; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.DataRecordSerializer; import org.jetel.data.Defaults; import org.jetel.data.Token; import org.jetel.data.formatter.CloverDataFormatter; import org.jetel.data.formatter.CloverDataFormatter.DataCompressAlgorithm; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.graph.ContextProvider; import org.jetel.metadata.DataRecordMetadata; import org.jetel.metadata.DataRecordMetadataXMLReaderWriter; import org.jetel.util.bytes.ByteBufferUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.file.FileUtils; import org.jetel.util.primitive.BitArray; import org.jetel.util.stream.CloverDataStream; import org.jetel.util.stream.StreamUtils; import org.jetel.util.string.StringUtils; public class CloverDataParser extends AbstractParser implements ICloverDataParser { public static class FileConfig { public byte majorVersion; public byte minorVersion; public byte revisionVersion; public int compressionAlgorithm; public CloverDataFormatter.DataFormatVersion formatVersion; public DataRecordMetadata metadata; public boolean raw; } private final static Log logger = LogFactory.getLog(CloverDataParser.class); private DataRecordMetadata metadata; private ReadableByteChannel recordFile; private CloverDataStream.Input input; private CloverBuffer recordBuffer; private InputStream inStream; private URL projectURL; private DataRecordSerializer serializer; private CloverDataFormatter.DataCompressAlgorithm compress; /** Clover version which has been used to create the input data file. */ private FileConfig version; private boolean useParsingFromJobflow_3_4 = false; /** * True, if the current transformation is jobflow. */ private boolean isJobflow; private final static int LONG_SIZE_BYTES = 8; private final static int LEN_SIZE_SPECIFIER = 4; public CloverDataParser(DataRecordMetadata metadata){ this.metadata = metadata; this.compress = DataCompressAlgorithm.NONE; } @Override public FileConfig getVersion() { return version; } public InputStream getInStream() { return inStream; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getNext() */ @Override public DataRecord getNext() throws JetelException { DataRecord record = DataRecordFactory.newRecord(metadata); record.init(); return getNext(record); } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#skip(int) */ @Override public int skip(int nRec) throws JetelException { if (nRec == 0) { return 0; } if (isDirectReadingSupported()) { CloverBuffer buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); for (int skipped = 0; skipped < nRec; skipped++) { if (!getNextDirect(buffer)) { return skipped; } } } else { DataRecord record = DataRecordFactory.newRecord(metadata); record.init(); for (int skipped = 0; skipped < nRec; skipped++) { if (getNext(record) == null) { return skipped; } } } return nRec; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#init(org.jetel.metadata.DataRecordMetadata) */ @Override public void init() throws ComponentNotReadyException { if (metadata == null) { throw new ComponentNotReadyException("Metadata are null"); } recordBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); recordBuffer.order(CloverDataFormatter.BUFFER_BYTE_ORDER); serializer=new CloverDataRecordSerializer(); } private void doReleaseDataSource() throws IOException { if (inStream != null) { inStream.close(); inStream = null; // setDataSource() tests inStream for null } } @Override protected void releaseDataSource() { try { doReleaseDataSource(); } catch (IOException ioe) { logger.warn("Failed to release data source", ioe); } } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) * * parameter: data fiele name or {data file name, index file name} */ @Override public void setDataSource(Object in) throws ComponentNotReadyException { String inData=null; if (releaseDataSource) { releaseDataSource(); } if (in instanceof InputStream) { inStream = (InputStream) in; }else if (in instanceof ReadableByteChannel){ inStream = Channels.newInputStream((ReadableByteChannel)in); }else if (in instanceof File){ try { inStream = new FileInputStream((File)in); } catch (IOException e) { throw new ComponentNotReadyException(e); } }else if (in instanceof String[]) { inData = ((String[])in)[0]; }else if (in instanceof String){ inData = (String)in; }else{ throw new ComponentNotReadyException("Unsupported Data Source type: "+in.getClass().getName()); } if (inStream==null) { // doReleaseDataSource() should set the previous stream to null try{ if (inData.startsWith("zip:")) { // CLO-4045 StringBuilder sbAnchor = new StringBuilder(); FileUtils.getArchiveType(inData, new StringBuilder(), sbAnchor); if (!StringUtils.isEmpty(sbAnchor)) { // CLO-4045: archive entry is already specified in the URL inStream = FileUtils.getInputStream(projectURL, inData); } else { String fileName = new File(FileUtils.getFile(projectURL, inData)).getName(); if (fileName.toLowerCase().endsWith(".zip")) { fileName = fileName.substring(0,fileName.lastIndexOf('.')); } try { // backward compatibility, append #DATA/fileName inStream = FileUtils.getInputStream(projectURL, inData + "#" + CloverDataFormatter.DATA_DIRECTORY + fileName); } catch (IOException ioe) { try { inStream = FileUtils.getInputStream(projectURL, inData); } catch (IOException ioe2) { ioe.addSuppressed(ioe2); throw ioe; } } } } else { inStream = FileUtils.getInputStream(projectURL, inData); } } catch (IOException ex) { throw new ComponentNotReadyException(ex); } } //read and check header of clover binary data format to check out the compatibility issues version = checkCompatibilityHeader(inStream, metadata); if(version.formatVersion!=CloverDataFormatter.CURRENT_FORMAT_VERSION){ return; } this.compress=DataCompressAlgorithm.getAlgorithm(version.compressionAlgorithm); //is the current transformation jobflow? isJobflow = ContextProvider.getRuntimeContext() != null && ContextProvider.getRuntimeContext().getJobType().isJobflow(); //special de-serialisation needs to be used, see CLO-1382 if (version.majorVersion == 3 && (version.minorVersion == 3 || version.minorVersion == 4) && isJobflow) { useParsingFromJobflow_3_4 = true; } switch(compress){ case NONE: this.input= new CloverDataStream.Input(inStream); break; case LZ4: this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorLZ4()); break; case GZIP: this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorGZIP()); break; default: throw new RuntimeException("Unsupported compression algorithm: "+compress); } } public static FileConfig checkCompatibilityHeader(ReadableByteChannel recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException { return checkCompatibilityHeader(Channels.newInputStream(recordFile),metadata); } public static FileConfig checkCompatibilityHeader(InputStream recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException { byte[] extraBytes; CloverBuffer buffer = CloverBuffer.wrap(new byte[CloverDataFormatter.CLOVER_DATA_HEADER_LENGTH]); try { int count = StreamUtils.readBlocking(recordFile, buffer.array()); if (count != buffer.capacity()) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } //read clover binary data header and check backward compatibility //better header description is at CloverDataFormatter.setDataTarget() method long cloverHash=buffer.getLong(); if (CloverDataFormatter.CLOVER_DATA_HEADER != cloverHash) { //clover binary data format is definitely incompatible with current version - header is not present throw new ComponentNotReadyException("Source clover data file is obsolete. Data cannot be read."); } long cloverDataCompatibilityHash = buffer.getLong(); FileConfig version = new FileConfig(); version.majorVersion = buffer.get(); version.minorVersion = buffer.get(); version.revisionVersion = buffer.get(); if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_2_9){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_29; }else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_3_5){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_35; }else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_4_0){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_40; }else{ throw new ComponentNotReadyException("Invallid Clover Data Compatibility Hash: "+cloverDataCompatibilityHash); } switch(version.formatVersion){ case VERSION_29: case VERSION_35: extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE_3_5]; try { int count = StreamUtils.readBlocking(recordFile, extraBytes); if (count != extraBytes.length) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) { throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read."); } // what's left is metadata serialized, will let this to "other" parser break; case VERSION_40: extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE]; try { int count = StreamUtils.readBlocking(recordFile, extraBytes); if (count != extraBytes.length) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) { throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read."); } version.compressionAlgorithm=BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_COMPRESSED_DATA); version.raw = BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_RAW_DATA) == 1; //check metadata (just read,do not control now) int metasize; try { metasize=ByteBufferUtils.decodeLength(recordFile); byte[] metadef=new byte[metasize]; if (StreamUtils.readBlocking(recordFile, metadef) != metasize){ throw new IOException("Not enough data in file."); } version.metadata=DataRecordMetadataXMLReaderWriter.readMetadata(new ByteArrayInputStream(metadef)); } catch (IOException e) { throw new ComponentNotReadyException("Unable to read metadata definition from CloverData file", e); } if (!metadata.equals(version.metadata, false)) { logger.error("Data structure of input file is not compatible with used metadata. File data structure: " + version.metadata.toStringDataTypes()); throw new ComponentNotReadyException("Data structure of input file is not compatible with used metadata. More details available in log."); } break; default: throw new ComponentNotReadyException("Source clover data file is not supported (version " + version.majorVersion + "." + version.minorVersion + "." + version.revisionVersion + "). Data cannot be read."); } return version; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#close() */ @Override public void close() { releaseDataSource(); } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord) */ @Override public DataRecord getNext(DataRecord record) throws JetelException { if (!getNextDirect(recordBuffer)) { return null; //end of file reached } if (!useParsingFromJobflow_3_4) { record.deserializeUnitary(recordBuffer,serializer); } else { record.deserialize(recordBuffer,serializer); } return record; } /** * Reads the next serialized record into the provided buffer. * The target buffer is cleared first. * <p> * The position of the target buffer will be set to 0 * and the limit will be set to the end of the serialized record. * </p><p> * Returns the provided buffer or <code>null</code> * if there is no record available. * </p> * * @param targetBuffer the target buffer * @return <code>targetBuffer</code> or <code>null</code> if no data available * @throws JetelException */ @Override public boolean getNextDirect(CloverBuffer targetBuffer) throws JetelException { final int size; try { size=ByteBufferUtils.decodeLength(input); if (size<0) return false; //end of file reached targetBuffer.clear(); // CLO-2657: //in case current transformation is jobflow, tokenId must be added to targetBuffer //since tokenId is not part of clover data file if (isJobflow) { Token.serializeTokenId(-1, targetBuffer); } targetBuffer.limit(targetBuffer.position() + size); if (input.read(targetBuffer)==-1){ throw new JetelException("Insufficient data in datastream."); } targetBuffer.flip(); } catch(IOException ex){ throw new JetelException(ex); } return true; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setExceptionHandler(org.jetel.exception.IParserExceptionHandler) */ @Override public void setExceptionHandler(IParserExceptionHandler handler) { } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getExceptionHandler() */ @Override public IParserExceptionHandler getExceptionHandler() { return null; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getPolicyType() */ @Override public PolicyType getPolicyType() { return null; } @Override public void reset() { close(); } @Override public Object getPosition() { return null; } @Override public void movePosition(Object position) { } public URL getProjectURL() { return projectURL; } public void setProjectURL(URL projectURL) { this.projectURL = projectURL; } @Override public void preExecute() throws ComponentNotReadyException { reset(); } @Override public void postExecute() throws ComponentNotReadyException { if (releaseDataSource) { releaseDataSource(); } } @Override public void free() { close(); } @Override public boolean nextL3Source() { return false; } @Override public boolean isDirectReadingSupported() { return getVersion().raw; } }
package seedu.todoList.logic.parser; import seedu.todoList.logic.commands.*; import seedu.todoList.commons.exceptions.IllegalValueException; import seedu.todoList.commons.util.StringUtil; import static seedu.todoList.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.todoList.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern task_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern task_DATATYPE_ARGS_FORMAT = Pattern.compile("(?<dataType>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern task_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "d/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$/" + " (?<isPriorityPrivate>p?)p/(?<priority>[^/]+)"); private static final Pattern event_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "d/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$/" + " (?<StartTime>p?)s/(?<StartTime>[^/]+)" + " (?<EndTime>p?)e/(?<EndTime>[^/]+)"); private static final Pattern deadline_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "d/^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$/" + " (?<EndTime>p?)e/(?<EndTime>[^/]+)"); public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(arguments); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher_task = task_DATA_ARGS_FORMAT.matcher(args.trim()); final Matcher matcher_event = event_DATA_ARGS_FORMAT.matcher(args.trim()); final Matcher matcher_deadline = deadline_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format /* * Check if input matches task, event or deadline */ if (matcher_task.matches()) { try { return new AddCommand( matcher_task.group("name"), matcher_task.group("date"), matcher_task.group("priority") ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } }else if(matcher_event.matches()){ try { return new AddCommand( matcher_event.group("name"), matcher_event.group("date"), matcher_event.group("startTime"), matcher_event.group("endTime") ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } }else if(matcher_deadline.matches()){ try { return new AddCommand( matcher_deadline.group("name"), matcher_deadline.group("date"), matcher_deadline.group("endTime") ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } }else{ return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } } /** * Extracts the new task's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete task command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { final Matcher matcher_dataType = task_DATATYPE_ARGS_FORMAT.matcher(args.trim()); Optional<String> dataType = parseDataType(args); Optional<Integer> index = parseIndex(args); if(!matcher_dataType.matches() && !dataType.isPresent() || !index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(dataType.get(), index.get()); } /** * Parses arguments in the context of the select task command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = task_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Returns the specified dataType in the {@code command} * Returns an {@code Optional.empty()} otherwise. */ private Optional<String> parseDataType(String command) { final Matcher matcher = task_DATATYPE_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String dataType = matcher.group("dataType"); if(!StringUtil.isUnsignedString(dataType)){ return Optional.empty(); } return Optional.of(dataType); } /** * Parses arguments in the context of the find task command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher_keywords = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); final Matcher matcher_dataType = task_DATATYPE_ARGS_FORMAT.matcher(args.trim()); Optional<String> dataType_Present = parseDataType(args); if (!matcher_keywords.matches() || !matcher_dataType.matches() && !dataType_Present.isPresent()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher_keywords.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); String dataType = matcher_dataType.group("dataType"); return new FindCommand(keywordSet, dataType); } }
package seedu.unburden.logic.parser; import java.text.DateFormat; import java.text.SimpleDateFormat; import static seedu.unburden.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.unburden.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.unburden.commons.exceptions.IllegalValueException; import seedu.unburden.commons.util.StringUtil; import seedu.unburden.logic.commands.*; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_NAME_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace /*private static final Pattern KEYWORDS_DATE_FORMAT = Pattern.compile("(?<dates>\\S+([0-9]{2}[/][0-9]{2}[/][0-9]{4})*)");*/ private static final Pattern KEYWORDS_DATE_FORMAT = Pattern.compile("(?<dates>[0-9]{2}[-][0-9]{2}[-][0-9]{4}$)"); private static final Pattern ADD_FORMAT_1 = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "(?<isDatePrivate>p?)d/(?<date>[^/]+)"+ "(?<isStartTimeArgumentsPrivate>p?)s/(?<startTimeArguments>[^/]+)"+ "(?<isEndTimeArgumentsPrivate>p?)e/(?<endTimeArguments>[^/]+)"+ "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags private static final Pattern ADD_FORMAT_2 = Pattern.compile("(?<name>[^/]+)" + "(?<isDatePrivate>p?)d/(?<date>[^/]+)"+ "(?<tagArguments>(?: t/[^/]+)*)"); private static final Pattern ADD_FORMAT_3 = Pattern.compile("(?<name>[^/]+)" + "(?<tagArguments>(?: t/[^/]+)*)"); private static final Pattern EDIT_FORMAT = Pattern.compile("(?<index>[^/]+)(?!$)" + "(d/(?<date>[^/]+))?" + "(s/(?<startTimeArguments>[^/]+))?" + "(e/(?<endTimeArguments>[^/]+))?"); private static final String byToday = "by today"; private static final String byTomorrow = "by tomorrow"; private static final String byNextWeek = "by next week"; private static final String byNextMonth = "by next month"; private static final String today = "today"; private static final String tomorrow = "tomorrow"; private static final String nextWeek = "next week"; private static final String nextMonth = "next month"; private static final DateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy"); public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord.toLowerCase()) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: return prepareSelect(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case DeleteCommand.COMMAND_WORD: return prepareDelete(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } /** * Parses arguments in the context of the add person command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ Calendar calendar = Calendar.getInstance(); final Matcher matcher1 = ADD_FORMAT_1.matcher(args.trim()); final Matcher matcher2 = ADD_FORMAT_2.matcher(args.trim()); final Matcher matcher3 = ADD_FORMAT_3.matcher(args.trim()); // Validate arg string format if (!matcher1.matches() & !matcher2.matches() & !matcher3.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { if(matcher1.matches()){ return new AddCommand( matcher1.group("name"), matcher1.group("date"), matcher1.group("startTimeArguments"), matcher1.group("endTimeArguments"), getTagsFromArgs(matcher1.group("tagArguments")) ); } else if(matcher2.matches()){ return new AddCommand( matcher2.group("name"), matcher2.group("date"), getTagsFromArgs(matcher2.group("tagArguments")) ); } else{ if(matcher3.group("name").toLowerCase().contains(byToday)){ return new AddCommand( matcher3.group("name").replaceAll("(?i)"+Pattern.quote(byToday), ""), dateFormatter.format(calendar.getTime()), getTagsFromArgs(matcher3.group("tagArguments")) ); } else if(matcher3.group("name").toLowerCase().contains(byTomorrow)){ calendar.setTime(calendar.getTime()); calendar.add(Calendar.DAY_OF_YEAR, 1); return new AddCommand( matcher3.group("name").replaceAll("(?i)"+Pattern.quote(byTomorrow), ""), dateFormatter.format(calendar.getTime()), getTagsFromArgs(matcher3.group("tagArguments")) ); } else if(matcher3.group("name").toLowerCase().contains(byNextWeek)){ calendar.setTime(calendar.getTime()); calendar.add(Calendar.WEEK_OF_YEAR, 1); return new AddCommand( matcher3.group("name").replaceAll("(?i)"+Pattern.quote(byNextWeek), ""), dateFormatter.format(calendar.getTime()), getTagsFromArgs(matcher3.group("tagArguments")) ); } else if(matcher3.group("name").toLowerCase().contains(byNextMonth)){ calendar.setTime(calendar.getTime()); calendar.add(Calendar.WEEK_OF_MONTH, 4); return new AddCommand( matcher3.group("name").replaceAll("(?i)"+Pattern.quote(byNextMonth), ""), dateFormatter.format(calendar.getTime()), getTagsFromArgs(matcher3.group("tagArguments")) ); } else{ return new AddCommand( matcher3.group("name"), getTagsFromArgs(matcher3.group("tagArguments")) ); } } } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Extracts the new person's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete person command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } private Command prepareEdit(String args) { final Matcher matcher = EDIT_FORMAT.matcher(args); if (!matcher.matches()) return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); String tempArgs = args.trim(); String[] newArgs = tempArgs.split(" ", 2); Optional<Integer> index = parseIndex(newArgs[0]); if (!index.isPresent()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } return new EditCommand(index.get(), newArgs[1].trim()); } /** * Parses arguments in the context of the select person command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<Integer> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<Integer> parseIndex(String command) { final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if(!StringUtil.isUnsignedInteger(index)){ return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Parses arguments in the context of the find person command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcherName = KEYWORDS_NAME_FORMAT.matcher(args.trim()); final Matcher matcherDate = KEYWORDS_DATE_FORMAT.matcher(args.trim()); if (!matcherName.matches() && !matcherDate.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } if(matcherDate.matches()){ final String keywords = matcherDate.group("dates"); final Set<String> dateKeyword = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(dateKeyword, "date"); } else{ //keywords delimited by whitespace Calendar calendar = Calendar.getInstance(); switch(matcherName.group("keywords").toLowerCase()){ case today: final String todayKeyword = dateFormatter.format(calendar.getTime()); final Set<String> todayKeywords = new HashSet<>(Arrays.asList(todayKeyword)); return new FindCommand(todayKeywords, "date"); case tomorrow: calendar.setTime(calendar.getTime()); calendar.add(Calendar.DAY_OF_YEAR, 1); final String tomorrowKeyword = dateFormatter.format(calendar.getTime()); final Set<String> tomorrowKeywords = new HashSet<>(Arrays.asList(tomorrowKeyword)); return new FindCommand(tomorrowKeywords, "date"); } final String[] nameKeywords = matcherName.group("keywords").split("\\s+"); final Set<String> nameKeyword = new HashSet<>(Arrays.asList(nameKeywords)); return new FindCommand(nameKeyword, "name"); } } }
package im.actor.messenger.storage.sqlite; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import java.util.List; import im.actor.model.storage.KeyValueRecord; import im.actor.model.storage.KeyValueStorage; public class SQLiteKeyValue implements KeyValueStorage { private SQLiteStatement insertStatement; private SQLiteStatement deleteStatement; private SQLiteDatabase db; private String name; public SQLiteKeyValue(SQLiteDatabase db, String name) { this.db = db; this.name = name; if (!SQLiteHelpers.isTableExists(db, name)) { db.execSQL("CREATE TABLE IF NOT EXISTS \"" + name + "\" (" + "\"ID\" INTEGER NOT NULL," + // 0: id "\"BYTES\" BLOB NOT NULL," + // 1: bytes "PRIMARY KEY(\"ID\"));"); } } private void checkInsertStatement() { if (insertStatement == null) { insertStatement = db.compileStatement("INSERT OR REPLACE INTO \"" + name + "\" " + "(\"ID\",\"BYTES\") VALUES (?,?)"); } } private void checkDeleteStatement() { if (deleteStatement == null) { deleteStatement = db.compileStatement("DELETE FROM \"" + name + "\" WHERE \"ID\"=?"); } } @Override public void addOrUpdateItem(long id, byte[] data) { checkInsertStatement(); db.beginTransaction(); try { insertStatement.bindLong(1, id); insertStatement.bindBlob(2, data); insertStatement.executeInsert(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void addOrUpdateItems(List<KeyValueRecord> values) { checkInsertStatement(); db.beginTransaction(); try { for (KeyValueRecord r : values) { insertStatement.bindLong(1, r.getId()); insertStatement.bindBlob(2, r.getData()); insertStatement.executeInsert(); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void removeItem(long id) { checkDeleteStatement(); db.beginTransaction(); try { deleteStatement.bindLong(1, id); deleteStatement.execute(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void removeItems(long[] ids) { checkDeleteStatement(); db.beginTransaction(); try { for (long id : ids) { deleteStatement.bindLong(1, id); deleteStatement.execute(); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void clear() { db.beginTransaction(); try { db.execSQL("DELETE FROM \"" + name + "\""); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public byte[] getValue(long id) { Cursor cursor = db.query("\"" + name + "\"", new String[]{"\"BYTES\""}, "\"ID\" = ?", new String[]{"" + id}, null, null, null); if (cursor == null) { return null; } try { if (cursor.moveToFirst()) { return cursor.getBlob(0); } } finally { cursor.close(); } return null; } }
package net.nemerosa.ontrack.extension.svn.service; import net.nemerosa.ontrack.extension.issues.IssueServiceRegistry; import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService; import net.nemerosa.ontrack.extension.issues.model.Issue; import net.nemerosa.ontrack.extension.svn.client.SVNClient; import net.nemerosa.ontrack.extension.svn.db.*; import net.nemerosa.ontrack.extension.svn.model.*; import net.nemerosa.ontrack.extension.svn.property.SVNBranchConfigurationProperty; import net.nemerosa.ontrack.extension.svn.property.SVNBranchConfigurationPropertyType; import net.nemerosa.ontrack.extension.svn.support.SVNUtils; import net.nemerosa.ontrack.model.structure.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; import java.util.stream.Collectors; import static net.nemerosa.ontrack.extension.svn.service.SVNServiceUtils.createChangeLogRevision; @Service @Transactional public class SVNServiceImpl implements SVNService { private final StructureService structureService; private final PropertyService propertyService; private final IssueServiceRegistry issueServiceRegistry; private final SVNConfigurationService configurationService; private final SVNRevisionDao revisionDao; private final SVNIssueRevisionDao issueRevisionDao; private final SVNEventDao eventDao; private final SVNRepositoryDao repositoryDao; private final SVNClient svnClient; @Autowired public SVNServiceImpl( StructureService structureService, PropertyService propertyService, IssueServiceRegistry issueServiceRegistry, SVNConfigurationService configurationService, SVNRevisionDao revisionDao, SVNIssueRevisionDao issueRevisionDao, SVNEventDao eventDao, SVNRepositoryDao repositoryDao, SVNClient svnClient) { this.structureService = structureService; this.propertyService = propertyService; this.issueServiceRegistry = issueServiceRegistry; this.configurationService = configurationService; this.revisionDao = revisionDao; this.issueRevisionDao = issueRevisionDao; this.eventDao = eventDao; this.repositoryDao = repositoryDao; this.svnClient = svnClient; } @Override public SVNRevisionInfo getRevisionInfo(SVNRepository repository, long revision) { TRevision t = revisionDao.get(repository.getId(), revision); return new SVNRevisionInfo( t.getRevision(), t.getAuthor(), t.getCreation(), t.getBranch(), t.getMessage(), repository.getRevisionBrowsingURL(t.getRevision()) ); } @Override public SVNRevisionPaths getRevisionPaths(SVNRepository repository, long revision) { // Gets the diff for the revision List<SVNRevisionPath> revisionPaths = svnClient.getRevisionPaths(repository, revision); return new SVNRevisionPaths( getRevisionInfo(repository, revision), revisionPaths); } @Override public List<Long> getRevisionsForIssueKey(SVNRepository repository, String key) { return issueRevisionDao.findRevisionsByIssue(repository.getId(), key); } @Override public SVNRepository getRepository(String name) { SVNConfiguration configuration = configurationService.getConfiguration(name); return SVNRepository.of( repositoryDao.getOrCreateByName(configuration.getName()), // The configuration contained in the property's configuration is obfuscated // and the original one must be loaded configuration, issueServiceRegistry.getConfiguredIssueService(configuration.getIssueServiceConfigurationIdentifier()) ); } @Override public Optional<SVNRepositoryIssue> searchIssues(SVNRepository repository, String token) { ConfiguredIssueService configuredIssueService = repository.getConfiguredIssueService(); if (configuredIssueService != null) { return issueRevisionDao.findIssueByKey(repository.getId(), token) .map(key -> new SVNRepositoryIssue( repository, configuredIssueService.getIssue(key) ) ); } else { return Optional.empty(); } } @Override public OntrackSVNIssueInfo getIssueInfo(String configurationName, String issueKey) { // Repository SVNRepository repository = getRepository(configurationName); // Issue service ConfiguredIssueService configuredIssueService = repository.getConfiguredIssueService(); if (configuredIssueService == null) { // No issue service configured return OntrackSVNIssueInfo.empty(repository.getConfiguration()); } // Gets the details about the issue Issue issue = configuredIssueService.getIssue(issueKey); // Gets the list of revisions & their basic info (order from latest to oldest) List<SVNChangeLogRevision> revisions = getRevisionsForIssueKey(repository, issueKey).stream() .map(revision -> { SVNRevisionInfo basicInfo = getRevisionInfo(repository, revision); return createChangeLogRevision( repository, basicInfo.getPath(), 0, revision, basicInfo.getMessage(), basicInfo.getAuthor(), basicInfo.getDateTime() ); }) .collect(Collectors.toList()); // Gets the last revision (which is the first in the list) SVNChangeLogRevision firstRevision = revisions.get(0); OntrackSVNRevisionInfo revisionInfo = getOntrackRevisionInfo(repository, firstRevision.getRevision()); // Merged revisions List<Long> merges = revisionDao.getMergesForRevision(repository.getId(), revisionInfo.getRevisionInfo().getRevision()); List<OntrackSVNRevisionInfo> mergedRevisionInfos = new ArrayList<>(); Set<String> paths = new HashSet<>(); for (long merge : merges) { // Gets the revision info OntrackSVNRevisionInfo mergeRevisionInfo = getOntrackRevisionInfo(repository, merge); // If the information contains as least one build, adds it if (!mergeRevisionInfo.getBuildViews().isEmpty()) { // Keeps only the first one for a given target path String path = mergeRevisionInfo.getRevisionInfo().getPath(); if (!paths.contains(path)) { mergedRevisionInfos.add(mergeRevisionInfo); paths.add(path); } } } return new OntrackSVNIssueInfo( repository.getConfiguration(), repository.getConfiguredIssueService().getIssueServiceConfigurationRepresentation(), issue, revisionInfo, mergedRevisionInfos ); } @Override public OntrackSVNRevisionInfo getOntrackRevisionInfo(SVNRepository repository, long revision) { // Gets information about the revision SVNRevisionInfo basicInfo = getRevisionInfo(repository, revision); SVNChangeLogRevision changeLogRevision = createChangeLogRevision( repository, basicInfo.getPath(), 0, revision, basicInfo.getMessage(), basicInfo.getAuthor(), basicInfo.getDateTime() ); // Gets the first copy event on this path after this revision SVNLocation firstCopy = getFirstCopyAfter(repository, basicInfo.toLocation()); // Data to collect Collection<BuildView> buildViews = new ArrayList<>(); // Loops over all authorised branches for (Project project : structureService.getProjectList()) { for (Branch branch : structureService.getBranchesForProject(project.getId())) { // Identifies a possible build given the path/revision and the first copy Optional<Build> build = lookupBuild(basicInfo.toLocation(), firstCopy, branch); // Build found if (build.isPresent()) { // Gets the build view BuildView buildView = structureService.getBuildView(build.get()); // Adds it to the list buildViews.add(buildView); } } } return new OntrackSVNRevisionInfo( repository.getConfiguration(), changeLogRevision, buildViews ); } private Optional<Build> lookupBuild(SVNLocation location, SVNLocation firstCopy, Branch branch) { // Gets the SVN configuration for the branch Property<SVNBranchConfigurationProperty> configurationProperty = propertyService.getProperty(branch, SVNBranchConfigurationPropertyType.class); if (configurationProperty.isEmpty()) { return Optional.empty(); } // Information String buildPathPattern = configurationProperty.getValue().getBuildPath(); // Revision path if (SVNUtils.isPathRevision(buildPathPattern)) { return getEarliestBuild(branch, location, buildPathPattern); } // Tag pattern else { // Uses the copy (if available) if (firstCopy != null) { return getEarliestBuild(branch, firstCopy, buildPathPattern); } else { return Optional.empty(); } } } private Optional<Build> getEarliestBuild(Branch branch, SVNLocation location, String buildPathPattern) { if (SVNUtils.followsBuildPattern(location, buildPathPattern)) { // Gets the build name String buildName = SVNUtils.getBuildName(location, buildPathPattern); /** * If the build is defined by path@revision, the earliest build is the one * that follows this revision. */ if (SVNUtils.isPathRevision(buildPathPattern)) { return structureService.findBuildAfterUsingNumericForm(branch.getId(), buildName); } /** * In any other case (tag or tag prefix), the build must be looked exactly */ else { return structureService.findBuildByName(branch.getProject().getName(), branch.getName(), buildName); } } else { return Optional.empty(); } } private SVNLocation getFirstCopyAfter(SVNRepository repository, SVNLocation location) { return eventDao.getFirstCopyAfter(repository.getId(), location); } }
//package org.RDKit; import org.junit.*; import static org.junit.Assert.*; import org.RDKit.*; public class WrapperTests { private ROMol mol1; @Before public void setUp() { String smiles="c1ccccc1"; mol1 = RDKFuncs.MolFromSmiles(smiles); } @Test public void testBasics() { assertTrue(mol1.getNumAtoms()==6); assertTrue(mol1.getNumBonds()==6); } @Test public void testAtoms() { assertTrue(mol1.getAtomWithIdx(0).getAtomicNum()==6); assertFalse(mol1.hasAtomBookmark(1)); mol1.setAtomBookmark(mol1.getAtomWithIdx(0),1); assertTrue(mol1.hasAtomBookmark(1)); } @Test public void testBonds() { assertTrue(mol1.getBondWithIdx(0).getBondType()==Bond.BondType.AROMATIC); } @Test public void testSmilesWrite() { String smi=RDKFuncs.MolToSmiles(mol1); assertEquals(smi,"c1ccccc1",smi); } @Test public void testReactionBasics() { ChemicalReaction rxn; rxn=RDKFuncs.ReactionFromSmarts("[OH][C:1]=[O:2].[N!H0:3]>>[N:3][C:1]=[O:2]"); assertTrue(rxn.getNumReactantTemplates()==2); assertTrue(rxn.getNumProductTemplates()==1); ROMol r1,r2; r1=RDKFuncs.MolFromSmiles("CC(=O)O"); r2=RDKFuncs.MolFromSmiles("ClCN"); assertTrue(r1.getNumAtoms()==4); assertTrue(r2.getNumAtoms()==3); ROMol_Vect rs= new ROMol_Vect(2); rs.set(0,r1); rs.set(1,r2); ROMol_Vect_Vect ps; ps=rxn.runReactants(rs); assertFalse(ps.isEmpty()); assertTrue(ps.size()==1); assertFalse(ps.get(0).isEmpty()); assertTrue(ps.get(0).size()==1); assertTrue(r1.getNumAtoms()==4); assertTrue(r2.getNumAtoms()==3); assertTrue(ps.get(0).get(0).getNumAtoms()==6); } @Test public void testSubstruct1() { ROMol p; Match_Vect mv; p = RDKFuncs.MolFromSmarts("c"); assertTrue(mol1.hasSubstructMatch(p)); mv=mol1.getSubstructMatch(p); assertTrue(mv.size()==1); assertTrue(mv.get(0).getFirst()==0); assertTrue(mv.get(0).getSecond()==0); } @Test public void testSubstruct2() { ROMol p; Match_Vect mv; p = RDKFuncs.MolFromSmarts("C"); assertFalse(mol1.hasSubstructMatch(p)); mv=mol1.getSubstructMatch(p); assertTrue(mv.size()==0); } @Test public void testSubstruct3() { ROMol p; Match_Vect mv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)CC"); p = RDKFuncs.MolFromSmarts("CN"); mv=m2.getSubstructMatch(p); assertTrue(mv.size()==2); assertTrue(mv.get(0).getFirst()==0); assertTrue(mv.get(0).getSecond()==1); assertTrue(mv.get(1).getFirst()==1); assertTrue(mv.get(1).getSecond()==0); } @Test public void testSubstruct4() { ROMol p; Match_Vect_Vect mvv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)CC"); p = RDKFuncs.MolFromSmarts("CN"); mvv=m2.getSubstructMatches(p); assertTrue(mvv.size()==1); assertTrue(mvv.get(0).size()==2); assertTrue(mvv.get(0).get(0).getFirst()==0); assertTrue(mvv.get(0).get(0).getSecond()==1); assertTrue(mvv.get(0).get(1).getFirst()==1); assertTrue(mvv.get(0).get(1).getSecond()==0); } @Test public void testSubstruct5() { ROMol p; Match_Vect_Vect mvv; ROMol m2; m2 = RDKFuncs.MolFromSmiles("NC(=O)NCC"); p = RDKFuncs.MolFromSmarts("[$(C=O)]N"); mvv=m2.getSubstructMatches(p); assertTrue(mvv.size()==2); assertTrue(mvv.get(0).size()==2); assertTrue(mvv.get(0).get(0).getFirst()==0); assertTrue(mvv.get(0).get(0).getSecond()==1); assertTrue(mvv.get(0).get(1).getFirst()==1); assertTrue(mvv.get(0).get(1).getSecond()==0); assertTrue(mvv.get(1).size()==2); assertTrue(mvv.get(1).get(0).getFirst()==0); assertTrue(mvv.get(1).get(0).getSecond()==1); assertTrue(mvv.get(1).get(1).getFirst()==1); assertTrue(mvv.get(1).get(1).getSecond()==3); } @Test public void testFingerprints1() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); ExplicitBitVect fp1,fp2; fp1=RDKFuncs.RDKFingerprintMol(m1); fp2=RDKFuncs.RDKFingerprintMol(m1); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)==1.0); fp2=RDKFuncs.RDKFingerprintMol(m2); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)<1.0); assertTrue(RDKFuncs.TanimotoSimilarityEBV(fp1,fp2)>0.0); } @Test public void testFingerprints2() { ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); m2 = RDKFuncs.MolFromSmiles("C1=CC=CC=N1"); SparseIntVectu32 fp1,fp2; fp1=RDKFuncs.MorganFingerprintMol(m1,2); fp2=RDKFuncs.MorganFingerprintMol(m1,2); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)==1.0); fp2=RDKFuncs.MorganFingerprintMol(m2,2); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)<1.0); assertTrue(RDKFuncs.DiceSimilaritySIVu32(fp1,fp2)>0.0); UInt_Pair_Vect v1=fp1.getNonzero(); assertTrue(v1.size()>0); UInt_Pair_Vect v2=fp2.getNonzero(); assertTrue(v2.size()>0); assertTrue(v2.size()>v1.size()); } @Test public void testErrorHandling() { ROMol m1; System.err.println("go"); m1 = RDKFuncs.MolFromSmiles("C1CC"); assertTrue(m1==null); System.err.println("go2"); m1 = RDKFuncs.MolFromSmiles("c1cc1"); assertTrue(m1==null); System.err.println("ok!"); } /* @Test public void testMemory() { for(int i=0;i<1000000;i++){ ROMol m1,m2; m1 = RDKFuncs.MolFromSmiles("C1=CC=CC=C1"); if((i%1000)==0){ System.err.println("done: "+i); } m1.delete(); } }*/ static { try { System.loadLibrary("RDKFuncs"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. Make sure that libRDKFuncs.so is somewhere in your LD_LIBRARY_PATH.\n" + e); System.exit(1); } } public static void main(String args[]) { org.junit.runner.JUnitCore.main("WrapperTests"); } }
package tigase.xmpp; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import java.util.logging.Level; import tigase.util.JIDUtils; import tigase.db.UserRepository; import tigase.db.UserAuthRepository; import tigase.db.TigaseDBException; import tigase.server.xmppsession.SessionManagerHandler; import tigase.db.AuthorizationException; /** * Describe class XMPPResourceConnection here. * * * Created: Wed Feb 8 22:30:37 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class XMPPResourceConnection extends RepositoryAccess { /** * Private logger for class instancess. */ private static final Logger log = Logger.getLogger("tigase.xmpp.XMPPResourceConnection"); private SessionManagerHandler loginHandler = null; private XMPPSession parentSession = null; //private LoginContext loginContext = null; /** * <code>sessionId</code> keeps XMPP stream session ID given at connection * initialization time. */ private String sessionId = null; private String defLang = "en"; /** * Session resource - part of user's JID for this session */ private String resource = null; /** * Value of <code>System.currentTimeMillis()</code> from the time when this * session last active from user side. */ private long lastAccessed = 0; private long creationTime = 0; private long authenticationTime = 0; private String domain = null; /** * This variable is to keep relates XMPPIOService ID only. */ private String connectionId = null; private int priority = 0; //private boolean dummy = false; private String userJid = null; private String userId = null; // private String[] anon_peers = null; private long id_counter = 0; private ConnectionStatus connectionStatus = ConnectionStatus.INIT; // private boolean onHold = false; /** * Session temporary data. All data stored in this <code>Map</code> disapear * when session finishes. */ private Map<String, Object> sessionData = null; /** * Creates a new <code>XMPPResourceConnection</code> instance. * * * @param connectionId * @param rep * @param authRepo * @param loginHandler * @param anon_allowed */ public XMPPResourceConnection(String connectionId, UserRepository rep, UserAuthRepository authRepo, SessionManagerHandler loginHandler, boolean anon_allowed) { super(rep, authRepo, anon_allowed); long currTime = System.currentTimeMillis(); this.connectionId = connectionId; this.loginHandler = loginHandler; this.creationTime = currTime; this.lastAccessed = currTime; sessionData = new ConcurrentHashMap<String, Object>(4, 0.9f); } public boolean isLocalDomain(String outDomain, boolean includeComponents) { return loginHandler.isLocalDomain(outDomain, includeComponents); } public void putCommonSessionData(String key, Object value) { if (parentSession != null) { parentSession.putCommonSessionData(key, value); } } /** * * @param key * @return */ public Object getCommonSessionData(String key) { return parentSession == null ? null : parentSession.getCommonSessionData(key); } public Object removeCommonSessionData(String key) { return parentSession == null ? null : parentSession.removeCommonSessionData(key); } public void setConnectionStatus(ConnectionStatus status) { connectionStatus = status; } public ConnectionStatus getConnectionStatus() { return connectionStatus; } // public void setOnHold() { // onHold = true; // public boolean isOnHold() { // return onHold; /** * Saves given session data. Data are saved to temporary storage only and are * accessible during this session life only and only from this session * instance.<br/> * Any <code>Object</code> can be stored and retrieved through * <code>getSessionData(...)</code>.<br/> * To access permanent storage to keep data between session instances you must * use one of <code>get/setData...(...)</code> methods familly. They gives you * access to hierachical permanent data base. Permanent data base however can * be accessed after successuf authorization while session storage is availble * all the time. * * @param key a <code>String</code> value of stored data key ID. * @param value a <code>Object</code> value of data stored in session. * @see #getSessionData(String) */ public final void putSessionData(final String key, final Object value) { lastAccessed = System.currentTimeMillis(); sessionData.put(key, value); } /** * Retrieves session data. * This method gives access to temporary session data only. * You can retrieve earlier saved data giving key ID to receive needed * value. Please see <code>putSessionData</code> description for more details. * * @param key a <code>String</code> value of stored data ID. * @return a <code>Object</code> value of data for given key. * @see #putSessionData(String, Object) */ public final Object getSessionData(final String key) { lastAccessed = System.currentTimeMillis(); return sessionData.get(key); } public final void removeSessionData(final String key) { lastAccessed = System.currentTimeMillis(); sessionData.remove(key); } public void setPriority(final int priority) { this.priority = priority; } public int getPriority() { return priority; } public void streamClosed() { if (parentSession != null) { parentSession.streamClosed(this); } // end of if (parentSession != null) parentSession = null; resource = null; sessionId = null; } public void setParentSession(final XMPPSession parent) { this.parentSession = parent; if (parentSession != null) { userId = JIDUtils.getNodeID(parentSession.getUserName(), domain); userJid = userId + (resource != null ? ("/" + resource) : "/" + sessionId); } } public XMPPSession getParentSession() { return parentSession; } // public void setAnonymousPeers(String[] peers) { // this.anon_peers = peers; // public String[] getAnonymousPeers() { // return anon_peers; /** * Returns full user JID for this session or throws * <code>NotAuthorizedException</code> if session is not authorized yet and * therefore user name and resource is not known yet. * * @return a <code>String</code> value of calculated user full JID for this * session including resource name. * @exception NotAuthorizedException when this session has not * been authorized yet and some parts of user JID are not known yet. */ public final String getJID() throws NotAuthorizedException { if (parentSession == null) { throw new NotAuthorizedException(NOT_AUTHORIZED_MSG); } // end of if (username == null) return userJid; } /** * Returns user JID but without <em>resource</em> part. This is real user ID * not session ID. * To retrieve session ID - full JID refer to <code>getJID()</code> * method.<br/> * If session has not been authorized yet this method throws * <code>NotAuthorizedException</code>. * * @return a <code>String</code> value of user ID - this is user JID without * resource part. To obtain full user JID please refer to <code>getJID</code> * method. * @exception NotAuthorizedException when this session has not * been authorized yet and some parts of user JID are not known yet. * @see #getJID() */ @Override public final String getUserId() throws NotAuthorizedException { if (parentSession == null) { throw new NotAuthorizedException(NOT_AUTHORIZED_MSG); } // end of if (username == null) return userId; } @Override public final String getUserName() throws NotAuthorizedException { if (parentSession == null) { throw new NotAuthorizedException(NOT_AUTHORIZED_MSG); } // end of if (username == null) return parentSession.getUserName(); } public List<XMPPResourceConnection> getActiveSessions() throws NotAuthorizedException { if (parentSession == null) { throw new NotAuthorizedException(NOT_AUTHORIZED_MSG); } // end of if (username == null) return parentSession.getActiveResources(); } public String[] getAllResourcesJIDs() throws NotAuthorizedException { if (parentSession == null) { throw new NotAuthorizedException(NOT_AUTHORIZED_MSG); } // end of if (username == null) return parentSession.getJIDs(); } public void setDomain(final String domain) { this.domain = domain; } public String getDomain() { return domain; } /** * Gets the value of sessionId * * @return the value of sessionId */ public String getSessionId() { return this.sessionId; } /** * Sets the value of sessionId * * @param argSessionId Value to assign to this.sessionId */ public void setSessionId(final String argSessionId) { this.sessionId = argSessionId; } public String getDefLang() { return this.defLang; } public void setDefLang(String lang) { this.defLang = lang; } public boolean isResourceSet() { return this.resource != null; } /** * Gets the value of resource * * @return the value of resource */ public String getResource() { return this.resource; } /** * Sets the value of resource * * @param argResource Value to assign to this.resource * @throws NotAuthorizedException */ public void setResource(final String argResource) throws NotAuthorizedException { this.resource = argResource; // There is really unlikely a parent session would be null here but it may // happen when the user disconnects just after sending resource bind. // Due to asynchronous nature of packets processing in the Tigase the // the authorization might be cancelled while resource bind packet still // waits in the queue..... // This has already happened.... if (parentSession != null) { parentSession.addResourceConnection(this); } userJid = getUserId() + (resource != null ? ("/" + resource) : "/" + sessionId); } /** * Gets the value of lastAccessed * * @return the value of lastAccessed */ public long getLastAccessed() { return this.lastAccessed; } /** * Sets the value of lastAccessed * * @param argLastAccessed Value to assign to this.lastAccessed */ public void setLastAccessed(final long argLastAccessed) { this.lastAccessed = argLastAccessed; } /** * Gets the value of connectionId * * @return the value of connectionId */ public String getConnectionId() { lastAccessed = System.currentTimeMillis(); return this.connectionId; } public String getConnectionId(String jid) { return ((parentSession == null || jid == null) ? this.connectionId : parentSession.getResourceConnection(jid).getConnectionId()); } @Override public final void logout() throws NotAuthorizedException { loginHandler.handleLogout(getUserName(), this); streamClosed(); super.logout(); } protected void login() { authenticationTime = System.currentTimeMillis(); } public long getAuthTime() { return authenticationTime - creationTime; } public long getCreationTime() { return creationTime; } public Authorization unregister(final String name_param) throws NotAuthorizedException, TigaseDBException { Authorization auth_res = super.unregister(name_param); // if (auth_res == Authorization.AUTHORIZED) { // List<XMPPResourceConnection> res_conn = // parentSession.getActiveResources(); // for (XMPPResourceConnection res: res_conn) { // if (res != this) { // res.logout(); // } // end of if (res != this) // } // end of for (XMPPResourceConnection res: res_conn) // logout(); // } // end of if (res == Authorization.AUTHORIZED) return auth_res; } @Override public final Authorization loginPlain(String user, String password) throws NotAuthorizedException, AuthorizationException, TigaseDBException { Authorization result = super.loginPlain(user, password); if (result == Authorization.AUTHORIZED) { loginHandler.handleLogin(user, this); } // end of if (result == Authorization.AUTHORIZED) return result; } @Override public final Authorization loginDigest(String user, String digest, String id, String alg) throws NotAuthorizedException, AuthorizationException, TigaseDBException { Authorization result = super.loginDigest(user, digest, id, alg); if (result == Authorization.AUTHORIZED) { loginHandler.handleLogin(user, this); } // end of if (result == Authorization.AUTHORIZED) return result; } @Override public final Authorization loginOther(Map<String, Object> props) throws NotAuthorizedException, AuthorizationException, TigaseDBException { Authorization result = super.loginOther(props); if (result == Authorization.AUTHORIZED) { String user = (String)props.get(UserAuthRepository.USER_ID_KEY); if (log.isLoggable(Level.FINEST)) { log.finest("UserAuthRepository.USER_ID_KEY: " + user); } String nick = JIDUtils.getNodeNick(user); if (nick == null) { nick = user; } // end of if (nick == null) loginHandler.handleLogin(nick, this); } // end of if (result == Authorization.AUTHORIZED) return result; } // public boolean isDummy() { // return dummy; // public void setDummy(boolean dummy) { // this.dummy = dummy; public String nextStanzaId() { return "tig" + (++id_counter); } @Override public void queryAuth(Map<String, Object> authProps) { super.queryAuth(authProps); } } // XMPPResourceConnection
package org.ctrip.ops.sysdev.filters; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import org.apache.log4j.Logger; import com.hubspot.jinjava.Jinjava; public class BaseFilter implements Runnable { private static final Logger logger = Logger.getLogger(BaseFilter.class .getName()); protected Map config; protected List<String> IF; protected ArrayBlockingQueue inputQueue; protected ArrayBlockingQueue outputQueue; protected Jinjava jinjava; public BaseFilter(Map config, ArrayBlockingQueue inputQueue) { this.config = config; this.IF = (List<String>) this.config.get("if"); this.jinjava = new Jinjava(); this.inputQueue = inputQueue; int queueSize = 1000; if (this.config.containsKey("queueSize")) { queueSize = (int) this.config.get("queueSize"); } this.outputQueue = new ArrayBlockingQueue(queueSize, false); this.prepare(); } protected void prepare() { }; protected void filter(Map event) { }; public void run() { while (true) { Map event = (Map) this.inputQueue.poll(); if (event != null) { boolean succuess = true; if (this.IF != null) { for (String c : this.IF) { if (this.jinjava.render(c, event = event).equals( "false")) { succuess = false; break; } } } if (succuess == false) { continue; } this.filter(event); try { this.outputQueue.put(event); } catch (InterruptedException e) { logger.warn("put event to outMQ failed"); logger.trace(e.getMessage()); } } } } public ArrayBlockingQueue getOutputMQ() { return this.outputQueue; } public static void main(String[] args) { Jinjava jinjava = new Jinjava(); long s = System.currentTimeMillis(); ArrayList a = new ArrayList(); final Map<String, Object> context = new HashMap(); context.put("message", "Ja-red"); context.put("@timestamp", 1442281327000L); context.put("array", new ArrayList() { { add("123"); } }); Map event = new HashMap() { { put("event", context); } }; for (int i = 0; i < 10000; i++) { jinjava.render("{{\"-\" in message}}", context); } System.out.println(System.currentTimeMillis() - s); System.out.println(jinjava.render( "{{event[\"@timestamp\"]|datetimeformat(\"%Y.%m\")}}", event = context)); System.out.println(jinjava.render( "{{\"-\" in message && \"X\" in message}}", event = context)); } }
package org.headsupdev.agile.framework; import org.headsupdev.agile.api.*; import org.headsupdev.agile.api.rest.Api; import org.headsupdev.agile.framework.rest.ConfigurationApi; import org.headsupdev.agile.web.LoadingPage; import org.headsupdev.agile.web.AbstractApplication; import org.headsupdev.agile.web.SystemEvent; import org.headsupdev.agile.framework.rest.ProjectApi; import org.headsupdev.agile.framework.error.*; import org.headsupdev.agile.framework.webdav.UploadArtifactEvent; import org.headsupdev.agile.framework.webdav.Artifact; import org.headsupdev.agile.security.permission.*; import org.headsupdev.agile.runtime.HeadsUpRuntime; import java.util.List; import java.util.LinkedList; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; /** * A placeholder application for the framework pages * * @author Andrew Williams * @since 1.0 */ public class HomeApplication extends AbstractApplication { private static Class<? extends Page>[] pages; private static Class<? extends Api>[] apis; private List<String> events = new LinkedList<String>(); private static BundleContext context; static { setupPages(); setupApis(); } protected static void setupPages() { Class<? extends Page>[] pages = (Class<? extends Page>[]) new Class[10]; pages[0] = LoadingPage.class; pages[1] = Login.class; pages[2] = Logout.class; pages[3] = Tasks.class; pages[4] = Updates.class; pages[5] = Setup.class; pages[6] = About.class; pages[7] = Error404Page.class; pages[8] = ErrorExpiredPage.class; pages[9] = ErrorInternalPage.class; setPages( pages ); } public static void setPages( Class<? extends Page>[] pages ) { HomeApplication.pages = pages; } protected static void setupApis() { Class<? extends Api>[] apis = (Class<? extends Api>[]) new Class[2]; apis[0] = ProjectApi.class; apis[1] = ConfigurationApi.class; setApis( apis ); } public static void setApis( Class<? extends Api>[] apis ) { HomeApplication.apis = apis; } public HomeApplication() { events.add( "system" ); } public String getName() { return "Home"; } public String getApplicationId() { return "home"; } @Override public Class[] getResources() { return new Class[]{ DynamicEmbed.class }; } public Class<? extends Page>[] getPages() { return (Class<? extends Page>[]) pages; } public Class<? extends Api>[] getApis() { return (Class<? extends Api>[]) apis; } public Class<? extends Page> getHomePage() { return LoadingPage.class; } @Override public Permission[] getPermissions() { return new Permission[] { new AdminPermission(), new ProjectListPermission(), new RepositoryReadPermission(), new RepositoryWritePermission(), new RepositoryReadAppPermission(), new RepositoryWriteAppPermission(), new TaskListPermission(), new AccountCreatePermission() }; } public String getDescription() { return null; } @Override public List<String> getEventTypes() { return events; } public List<MenuLink> getLinks( Project project ) { return new LinkedList<MenuLink>(); } public Class[] getPersistantClasses() { return new Class[] { UploadArtifactEvent.class, SystemEvent.class, Artifact.class }; } public BundleContext getContext() { return context; } static void setContext( BundleContext context ) { HomeApplication.context = context; } public static HeadsUpRuntime getHeadsUpRuntime() { ServiceReference sr = context.getServiceReference( HeadsUpRuntime.class.getName() ); return (HeadsUpRuntime) context.getService( sr ); } }
package aima.gui.fx.applications.search.games; import aima.gui.fx.framework.IntegrableApplication; import aima.gui.fx.views.SudokuViewCtrl; import javafx.scene.layout.Pane; import javafx.scene.layout.StackPane; /** * Simple Sudoku puzzle application. It provides a playground for programming * experiments with CSP algorithms. But note that no CSP implementation is included here. * * @author Ruediger Lunde */ public class SimpleSudokuApp extends IntegrableApplication { public final static String puzzle1 = "" + "53..7...." + "6..195..." + ".98....6." + "8...6...3" + "4..8.3..1" + "7...2...6" + ".6....28." + "...419..5" + "....8..79"; public final static String puzzle2 = "" + ".3......." + "...195..." + "..8....6." + "8...6...." + "4..8....1" + "....2...." + ".6....28." + "...419..5" + ".......7."; public final static String puzzle3 = "" + ".....9.7." + "....82.5." + "327....4." + ".16.4...." + ".5....3.." + "....9.7.." + "...6....5" + "8.2......" + "..42....8"; public static void main(String[] args) { launch(args); } protected SudokuViewCtrl stateViewCtrl; @Override public String getTitle() { return "Simple Sudoku App"; } @Override public Pane createRootPane() { StackPane root = new StackPane(); stateViewCtrl = new SudokuViewCtrl(root); return root; } @Override public void initialize() { initView(puzzle1); } @Override public void cleanup() { } protected void initView(String puzzle) { stateViewCtrl.clear(true); for (int i = 0; i < puzzle.length(); i++) { char ch = puzzle.charAt(i); if (ch >= '1' && ch <= '9') stateViewCtrl.fixDigit(i % 9 + 1, i / 9 + 1, ch - '0'); } } }
package org.eclipse.scanning.test.malcolm.real; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.dawnsci.analysis.api.roi.IROI; import org.eclipse.dawnsci.analysis.dataset.roi.CircularROI; import org.eclipse.scanning.api.malcolm.IMalcolmDevice; import org.eclipse.scanning.api.malcolm.IMalcolmService; import org.eclipse.scanning.api.malcolm.MalcolmTable; import org.eclipse.scanning.api.malcolm.attributes.MalcolmAttribute; import org.eclipse.scanning.api.malcolm.attributes.StringAttribute; import org.eclipse.scanning.api.malcolm.attributes.TableAttribute; import org.eclipse.scanning.api.points.IMutator; import org.eclipse.scanning.api.points.IPointGenerator; import org.eclipse.scanning.api.points.IPointGeneratorService; import org.eclipse.scanning.api.points.models.BoundingBox; import org.eclipse.scanning.api.points.models.CompoundModel; import org.eclipse.scanning.api.points.models.SpiralModel; import org.eclipse.scanning.connector.epics.EpicsV4ConnectorService; import org.eclipse.scanning.example.malcolm.ExampleMalcolmDevice; import org.eclipse.scanning.example.malcolm.ExampleMalcolmModel; import org.eclipse.scanning.malcolm.core.MalcolmService; import org.eclipse.scanning.points.PointGeneratorService; import org.eclipse.scanning.points.mutators.FixedDurationMutator; import org.epics.pvdata.factory.FieldFactory; import org.epics.pvdata.factory.PVDataFactory; import org.epics.pvdata.pv.PVDouble; import org.epics.pvdata.pv.PVDoubleArray; import org.epics.pvdata.pv.PVStringArray; import org.epics.pvdata.pv.PVStructure; import org.epics.pvdata.pv.PVUnion; import org.epics.pvdata.pv.ScalarType; import org.epics.pvdata.pv.Structure; import org.epics.pvdata.pv.Union; import org.junit.Ignore; import org.junit.Test; public class ExampleMalcolmDeviceTest { private EpicsV4ConnectorService connectorService; private IMalcolmService service; private ExampleMalcolmDevice dummyMalcolmDevice; /** * Starts an instance of the ExampleMalcolmDevice and then probes it with the configure() and call() methods * as well as getting a list of all attributes and several specific attributes * @throws Exception */ @Test public void configureAndRunDummyMalcolm() throws Exception { try { // Setup the objects this.connectorService = new EpicsV4ConnectorService(); // The real service, get it from OSGi outside this test! // Not required in OSGi mode (do not add this to your real code GET THE SERVICE FROM OSGi!) this.service = new MalcolmService(connectorService, null); // Start the dummy test device new Thread(new DeviceRunner()).start(); // Get the device IMalcolmDevice<ExampleMalcolmModel> modelledDevice = service.getDevice(getTestDeviceName()); // Setup the model and other configuration items List<IROI> regions = new LinkedList<>(); regions.add(new CircularROI(2, 6, 1)); regions.add(new CircularROI(4, 8, 9)); List<IMutator> mutators = new LinkedList<>(); mutators.add(new FixedDurationMutator(23.1)); IPointGeneratorService pgService = new PointGeneratorService(); IPointGenerator<SpiralModel> temp = pgService .createGenerator(new SpiralModel("stage_x", "stage_y", 1, new BoundingBox(0, -5, 8, 3)), regions); IPointGenerator<?> scan = pgService.createCompoundGenerator(temp); CompoundModel<?> cm = (CompoundModel<?>) scan.getModel(); cm.setMutators(mutators); ExampleMalcolmModel pmac1 = new ExampleMalcolmModel(); pmac1.setExposure(45f); pmac1.setGenerator(scan); // Call configure modelledDevice.configure(pmac1); // Call run modelledDevice.run(null); // Get a list of all attributes on the device List<MalcolmAttribute> attribs = modelledDevice.getAllAttributes(); assertEquals(10, attribs.size()); boolean stateFound = false; boolean statusFound = false; boolean busyFound = false; boolean totalStepsFound = false; boolean aFound = false; boolean bFound = false; boolean axesFound = false; boolean datasetsFound = false; boolean generatorFound = false; boolean completedStepsFound = false; boolean aIsNotWriteable = false; boolean bIsWriteable = false; for (MalcolmAttribute ma : attribs) { if (ma.getName().equals("state")) { stateFound = true; } else if (ma.getName().equals("status")) { statusFound = true; } else if (ma.getName().equals("busy")) { busyFound = true; } else if (ma.getName().equals("totalSteps")) { totalStepsFound = true; } else if (ma.getName().equals("A")) { aFound = true; aIsNotWriteable = !ma.isWriteable(); } else if (ma.getName().equals("B")) { bFound = true; bIsWriteable = ma.isWriteable(); } else if (ma.getName().equals("axesToMove")) { axesFound = true; } else if (ma.getName().equals("datasets")) { datasetsFound = true; } else if (ma.getName().equals("generator")) { generatorFound = true; } else if (ma.getName().equals("completedSteps")) { completedStepsFound = true; } } assertTrue(stateFound); assertTrue(statusFound); assertTrue(busyFound); assertTrue(totalStepsFound); assertTrue(aFound); assertTrue(aIsNotWriteable); assertTrue(bFound); assertTrue(bIsWriteable); assertTrue(axesFound); assertTrue(datasetsFound); assertTrue(generatorFound); assertTrue(completedStepsFound); // Get a specific choice (string) attribute Object stateValue = modelledDevice.getAttributeValue("state"); if (stateValue instanceof String) { String stateValueStr = (String) stateValue; assertEquals("READY", stateValueStr); } else { fail("state value was expected to be a string but wasn't"); } // Get a specific string attribute Object statusValue = modelledDevice.getAttributeValue("status"); if (statusValue instanceof String) { String statusValueStr = (String) statusValue; assertEquals("Test Status", statusValueStr); } else { fail("status value was expected to be a string but wasn't"); } // Get a specific boolean attribute Object busyValue = modelledDevice.getAttributeValue("busy"); if (busyValue instanceof Boolean) { Boolean busyValueBool = (Boolean) busyValue; assertTrue(busyValueBool.equals(false)); } else { fail("busy value was expected to be a boolean but wasn't"); } // Get a specific number attribute Object totalStepsValue = modelledDevice.getAttributeValue("totalSteps"); if (totalStepsValue instanceof Integer) { Integer totalStepsValueInt = (Integer) totalStepsValue; assertEquals((Integer)123, totalStepsValueInt); } else { fail("totalSteps value was expected to be an int but wasn't"); } // Get a specific string attribute (full attribute) Object statusAttributeValue = modelledDevice.getAttribute("status"); if (statusAttributeValue instanceof StringAttribute) { StringAttribute statusAttributeValueStr = (StringAttribute) statusAttributeValue; assertEquals("status", statusAttributeValueStr.getName()); assertEquals("Test Status", statusAttributeValueStr.getValue()); } else { fail("status value was expected to be a StringAttribute but wasn't"); } // Get a specific table attribute (full attribute) Object datasetsAttributeValue = modelledDevice.getAttribute("datasets"); if (datasetsAttributeValue instanceof TableAttribute) { TableAttribute datasetAttributeValueTable = (TableAttribute) datasetsAttributeValue; assertEquals("datasets", datasetAttributeValueTable.getName()); MalcolmTable malcolmTable = datasetAttributeValueTable.getValue(); assertEquals(4, malcolmTable.getHeadings().size()); assertEquals("detector", malcolmTable.getHeadings().get(0)); assertEquals("filename", malcolmTable.getHeadings().get(1)); assertEquals("dataset", malcolmTable.getHeadings().get(2)); assertEquals("users", malcolmTable.getHeadings().get(3)); assertEquals(3, malcolmTable.getColumn("dataset").size()); assertEquals("/entry/detector/I200", malcolmTable.getColumn("dataset").get(0)); assertEquals("/entry/detector/Iref", malcolmTable.getColumn("dataset").get(1)); assertEquals("/entry/detector/det1", malcolmTable.getColumn("dataset").get(2)); } else { fail("datasets value was expected to be a TableAttribute but wasn't"); } // Check the RPC calls were received correctly by the device Map<String, PVStructure> rpcCalls = dummyMalcolmDevice.getReceivedRPCCalls(); assertEquals(2, rpcCalls.size()); // configure PVStructure configureCall = rpcCalls.get("configure"); Union union = FieldFactory.getFieldCreate().createVariantUnion(); Structure generatorStructure = FieldFactory.getFieldCreate().createFieldBuilder() .addArray("mutators", union) .addArray("generators", union) .addArray("excluders", union) .setId("scanpointgenerator:generator/CompoundGenerator:1.0").createStructure(); Structure spiralGeneratorStructure = FieldFactory.getFieldCreate().createFieldBuilder() .addArray("centre", ScalarType.pvDouble) .add("scale", ScalarType.pvDouble) .add("units", ScalarType.pvString) .addArray("names", ScalarType.pvString) .add("alternate_direction", ScalarType.pvBoolean) .add("radius", ScalarType.pvDouble) .setId("scanpointgenerator:generator/SpiralGenerator:1.0").createStructure(); Structure fixedMutatorStructure = FieldFactory.getFieldCreate().createFieldBuilder() .add("duration", ScalarType.pvDouble) .setId("scanpointgenerator:mutator/FixedDurationMutator:1.0").createStructure(); Structure circularRoiStructure = FieldFactory.getFieldCreate().createFieldBuilder(). addArray("centre", ScalarType.pvDouble). add("radius", ScalarType.pvDouble). setId("scanpointgenerator:roi/CircularROI:1.0"). createStructure(); Structure excluderStructure = FieldFactory.getFieldCreate().createFieldBuilder(). addArray("scannables", ScalarType.pvString). add("roi", circularRoiStructure). createStructure(); Structure configureStructure = FieldFactory.getFieldCreate().createFieldBuilder() .add("exposure", ScalarType.pvFloat) .add("generator", generatorStructure) .createStructure(); PVStructure spiralGeneratorPVStructure = PVDataFactory.getPVDataCreate() .createPVStructure(spiralGeneratorStructure); double[] centre = new double[] { 6, 4 }; spiralGeneratorPVStructure.getSubField(PVDoubleArray.class, "centre").put(0, centre.length, centre, 0); spiralGeneratorPVStructure.getDoubleField("scale").put(1.0); spiralGeneratorPVStructure.getStringField("units").put("mm"); String[] names = new String[] { "stage_x", "stage_y" }; spiralGeneratorPVStructure.getSubField(PVStringArray.class, "names").put(0, names.length, names, 0); spiralGeneratorPVStructure.getBooleanField("alternate_direction").put(false); spiralGeneratorPVStructure.getDoubleField("radius").put(10.816653826391969); PVStructure fixedMutatorPVStructure = PVDataFactory.getPVDataCreate() .createPVStructure(fixedMutatorStructure); fixedMutatorPVStructure.getDoubleField("duration").put(23.1); PVStructure configurePVStructure = PVDataFactory.getPVDataCreate().createPVStructure(configureStructure); PVUnion pvu1 = PVDataFactory.getPVDataCreate().createPVVariantUnion(); pvu1.set(spiralGeneratorPVStructure); PVUnion[] unionArray = new PVUnion[1]; unionArray[0] = pvu1; configurePVStructure.getUnionArrayField("generator.generators").put(0, unionArray.length, unionArray, 0); PVUnion pvu2 = PVDataFactory.getPVDataCreate().createPVVariantUnion(); pvu2.set(fixedMutatorPVStructure); PVUnion[] unionArray2 = new PVUnion[1]; unionArray2[0] = pvu2; configurePVStructure.getUnionArrayField("generator.mutators").put(0, unionArray2.length, unionArray2, 0); configurePVStructure.getFloatField("exposure").put(45.0f); PVStructure expectedExcluder1PVStructure = PVDataFactory.getPVDataCreate().createPVStructure(excluderStructure); PVStringArray scannables1Val = expectedExcluder1PVStructure.getSubField(PVStringArray.class, "scannables"); String[] scannables1 = new String[] {"stage_x", "stage_y"}; scannables1Val.put(0, scannables1.length, scannables1, 0); PVStructure expectedROIPVStructure1 = expectedExcluder1PVStructure.getStructureField("roi"); PVDoubleArray cr1CentreVal = expectedROIPVStructure1.getSubField(PVDoubleArray.class, "centre"); double[] cr1Centre = new double[] {6, 1}; cr1CentreVal.put(0, cr1Centre.length, cr1Centre, 0); PVDouble radius1Val = expectedROIPVStructure1.getSubField(PVDouble.class, "radius"); radius1Val.put(2); PVStructure expectedExcluder2PVStructure = PVDataFactory.getPVDataCreate().createPVStructure(excluderStructure); PVStringArray scannables2Val = expectedExcluder2PVStructure.getSubField(PVStringArray.class, "scannables"); String[] scannables2 = new String[] {"stage_x", "stage_y"}; scannables2Val.put(0, scannables2.length, scannables2, 0); PVStructure expectedROIPVStructure2 = expectedExcluder2PVStructure.getStructureField("roi"); PVDoubleArray cr2CentreVal = expectedROIPVStructure2.getSubField(PVDoubleArray.class, "centre"); double[] cr2Centre = new double[] {8, 9}; cr2CentreVal.put(0, cr2Centre.length, cr2Centre, 0); PVDouble radius2Val = expectedROIPVStructure2.getSubField(PVDouble.class, "radius"); radius2Val.put(4); PVUnion[] crUnionArray = new PVUnion[2]; crUnionArray[0] = PVDataFactory.getPVDataCreate().createPVUnion(union); crUnionArray[0].set(expectedExcluder1PVStructure); crUnionArray[1] = PVDataFactory.getPVDataCreate().createPVUnion(union); crUnionArray[1].set(expectedExcluder2PVStructure); // TODO Put back in when excluders are fixed in python //configurePVStructure.getUnionArrayField("generator.excluders").put(0, crUnionArray.length, crUnionArray, 0); assertEquals(configureStructure, configureCall.getStructure()); assertEquals(configurePVStructure, configureCall); // run PVStructure runCall = rpcCalls.get("run"); Structure runStructure = FieldFactory.getFieldCreate().createFieldBuilder().createStructure(); PVStructure runPVStructure = PVDataFactory.getPVDataCreate().createPVStructure(runStructure); assertEquals(runStructure, runCall.getStructure()); assertEquals(runPVStructure, runCall); modelledDevice.dispose(); } catch (Exception ex) { ex.printStackTrace(); fail(ex.getMessage()); } finally { // Stop the device dummyMalcolmDevice.stop(); } } public class DeviceRunner implements Runnable { public void run() { String deviceName = getTestDeviceName(); dummyMalcolmDevice = new ExampleMalcolmDevice(deviceName); dummyMalcolmDevice.start(); } } private String getTestDeviceName() { String deviceName = "DummyMalcolmDevice"; Map<String, String> env = System.getenv(); if (env.containsKey("COMPUTERNAME")) deviceName = env.get("COMPUTERNAME"); else if (env.containsKey("HOSTNAME")) deviceName = env.get("HOSTNAME"); return deviceName.replace('.', ':') + ":malcolmTest"; } }
package org.jcryptool.crypto.keystore.ui.views.nodes; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.security.KeyStoreException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.bind.JAXBException; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.crypto.keys.KeyType; import org.jcryptool.crypto.keystore.KeyStorePlugin; import org.jcryptool.crypto.keystore.backend.KeyStoreAlias; import org.jcryptool.crypto.keystore.backend.KeyStoreManager; import org.jcryptool.crypto.keystore.descriptors.interfaces.IContactDescriptor; import org.jcryptool.crypto.keystore.ui.views.interfaces.IKeyStoreListener; public class ContactManager { /** Singleton instance */ private static ContactManager instance; private static ContactStore contactStore; /** All contacts and their respective meta information */ private Map<String, IContactDescriptor> contactsDesc = Collections .synchronizedMap(new HashMap<String, IContactDescriptor>()); private static List<IKeyStoreListener> listeners = new ArrayList<IKeyStoreListener>(); private ITreeNode invisibleRoot; private static String USER_CONTACTS_XML; private ContactManager() { try { USER_CONTACTS_XML = Platform.getInstanceLocation().getURL().getPath() + "contacts.xml"; IFileStore userContacts = EFS.getLocalFileSystem().fromLocalFile(new File(USER_CONTACTS_XML)); if(!userContacts.fetchInfo().exists()) { URL url = FileLocator.find(Platform.getBundle(KeyStorePlugin.PLUGIN_ID), new Path("contactstore/contacts.xml"), null); try { url = FileLocator.toFileURL(url); } catch (IOException e) { // LogUtil.logError(KeyStorePlugin.PLUGIN_ID, Messages.ContactManager_0, e, true); } IFileStore defaultContacts = EFS.getLocalFileSystem().fromLocalFile(new File(url.getPath())); defaultContacts.copy(userContacts, 0, null); } } catch (Exception e) { // LogUtil.logError(KeyStorePlugin.PLUGIN_ID, Messages.ContactManager_5, e, true); } } public synchronized static ContactManager getInstance() { if (instance == null) { instance = new ContactManager(); instance.initTreeModel(); } return instance; } private void initTreeModel() { if (invisibleRoot == null) { init(); invisibleRoot = new TreeNode("INVISIBLE_ROOT"); //$NON-NLS-1$ for (IContactDescriptor desc : contactsDesc.values()) { if (desc instanceof ContactDescriptorNode) { LogUtil.logInfo("adding: " + desc.getContact().getName()); //$NON-NLS-1$ invisibleRoot.addChild((ContactDescriptorNode) desc); } } LogUtil.logInfo("children.length: " + invisibleRoot.getChildrenArray().length); //$NON-NLS-1$ } } public void addKeyStoreListener(IKeyStoreListener listener) { listeners.add(listener); } public void removeKeyStoreListener(IKeyStoreListener listener) { listeners.remove(listener); } public Iterator<IKeyStoreListener> getKeyStoreListeners() { return listeners.iterator(); } public ITreeNode getTreeModel() { return invisibleRoot; } private void init() { try { contactsDesc = loadContacts(getContactStore()); } catch (Exception ex) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "Failed to load contacts", ex, true); return; } Enumeration<String> aliases = null; try { aliases = KeyStoreManager.getInstance().getAliases(); } catch (KeyStoreException e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "KeyStoreException while accessing the aliases", e, true); //$NON-NLS-1$ } Map<String, List<KeyStoreAlias>> aliasesHashed = new HashMap<String,List<KeyStoreAlias>>(); while(aliases.hasMoreElements()) { KeyStoreAlias alias = new KeyStoreAlias(aliases.nextElement()); if(!aliasesHashed.containsKey(alias.getContactName())) aliasesHashed.put(alias.getContactName(), new ArrayList<KeyStoreAlias>()); aliasesHashed.get(alias.getContactName()).add(alias); } for(Entry<String, IContactDescriptor> entry : contactsDesc.entrySet()) { if(aliasesHashed.containsKey(entry.getKey())) { for(KeyStoreAlias alias : aliasesHashed.get(entry.getKey())) addEntryToContact(entry.getValue(), alias); } } notifyListeners(); } private Map<String, IContactDescriptor> loadContacts(ContactStore cStore) throws FileNotFoundException, JAXBException { Map<String, IContactDescriptor> contacts = Collections .synchronizedMap(new HashMap<String, IContactDescriptor>()); for(Contact contact : getContactStore().getContacts()) contacts.put(contact.getName(), new ContactDescriptorNode(contact)); return contacts; } private void storeContacts(ContactStore cStore) throws JAXBException { cStore.write(USER_CONTACTS_XML); } private ContactStore getContactStore() throws FileNotFoundException, JAXBException { if(contactStore == null) contactStore = ContactStore.read(USER_CONTACTS_XML); return contactStore; } private void addEntryToContact(IContactDescriptor contact, KeyStoreAlias alias) { LogUtil.logInfo("Adding entry to contact " + alias.getAliasString()); //$NON-NLS-1$ if (alias.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) { contact.addSecretKey(alias); } else if (alias.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) { contact.addCertificate(alias); } else if (alias.getKeyStoreEntryType().equals(KeyType.KEYPAIR_PRIVATE_KEY)) { contact.addKeyPair(alias, null); } else if (alias.getKeyStoreEntryType().equals(KeyType.KEYPAIR_PUBLIC_KEY)) { contact.addKeyPair(null, alias); } } public boolean contactExists(String name) { return contactsDesc.containsKey(name); } public IContactDescriptor newContact(String name) { Contact contact = new Contact(); contact.setName(name); return newContact(contact); } public IContactDescriptor newContact(Contact contact) { IContactDescriptor newContactDesc = new ContactDescriptorNode(contact); addContact(newContactDesc); return newContactDesc; } private void addContact(IContactDescriptor contactDesc) { if (contactExists(contactDesc.getContact().getName())) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "Contact already exists", null, true); //$NON-NLS-1$ return; } try { getContactStore().getContacts().add(contactDesc.getContact()); storeContacts(getContactStore()); } catch (Exception e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "Exception while adding contact", e, true); return; } invisibleRoot.addChild((ContactDescriptorNode)contactDesc); contactsDesc.put(contactDesc.getContact().getName(), contactDesc); notifyListeners(); } public void removeContact(String contactName) { LogUtil.logInfo("Removing contact " + contactName); //$NON-NLS-1$ try { for(Contact c : getContactStore().getContacts()) { if(c.getName().equals(contactName)) { getContactStore().getContacts().remove(c); break; } } storeContacts(getContactStore()); } catch (Exception e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "Exception while removing contact", e, true); return; } invisibleRoot.removeChild((ContactDescriptorNode) contactsDesc.get(contactName)); contactsDesc.remove(contactName); notifyListeners(); } private void notifyListeners() { Iterator<IKeyStoreListener> it = getKeyStoreListeners(); while (it.hasNext()) { it.next().fireKeyStoreModified(invisibleRoot); } } public void removeEntry(KeyStoreAlias alias) { LogUtil.logInfo("Removing entry " + alias.getAliasString()); //$NON-NLS-1$ if (alias.getKeyStoreEntryType().equals(KeyType.SECRETKEY)) { LogUtil.logInfo("removing a secret key"); //$NON-NLS-1$ contactsDesc.get(alias.getContactName()).removeSecretKey(alias); } else if (alias.getKeyStoreEntryType().equals(KeyType.PUBLICKEY)) { LogUtil.logInfo("removing a certificate"); //$NON-NLS-1$ contactsDesc.get(alias.getContactName()).removeCertificate(alias); } else if (alias.getKeyStoreEntryType().equals(KeyType.KEYPAIR_PRIVATE_KEY)) { LogUtil.logInfo("removing a key pair"); //$NON-NLS-1$ contactsDesc.get(alias.getContactName()).removeKeyPair(alias); } else if (alias.getKeyStoreEntryType().equals(KeyType.KEYPAIR_PUBLIC_KEY)) { LogUtil.logInfo("removing a key pair"); //$NON-NLS-1$ contactsDesc.get(alias.getContactName()).removeKeyPair(alias); } notifyListeners(); } public void addCertificate(KeyStoreAlias alias) { LogUtil.logInfo("Adding certificate " + alias.getAliasString()); //$NON-NLS-1$ if (contactExists(alias.getContactName())) { contactsDesc.get(alias.getContactName()).addCertificate(alias); } else { IContactDescriptor contact = newContact(new Contact(alias.getContactName(), null, null, null, null)); contact.addCertificate(alias); } notifyListeners(); } public void addKeyPair(KeyStoreAlias privateKey, KeyStoreAlias publicKey) { LogUtil.logInfo("Adding key pair " + publicKey.getAliasString()); //$NON-NLS-1$ if (contactExists(privateKey.getContactName())) { contactsDesc.get(privateKey.getContactName()).addKeyPair(privateKey, publicKey); } else { IContactDescriptor contact = newContact(new Contact(privateKey.getContactName(), null, null, null, null) ); contact.addKeyPair(privateKey, publicKey); } notifyListeners(); } public void addSecretKey(KeyStoreAlias alias) { LogUtil.logInfo("Adding secret key " + alias.getAliasString()); //$NON-NLS-1$ if (contactExists(alias.getContactName())) { contactsDesc.get(alias.getContactName()).addSecretKey(alias); } else { IContactDescriptor contact = newContact(new Contact(alias.getContactName(), null, null, null, null)); contact.addSecretKey(alias); } notifyListeners(); } public Iterator<Contact> getContacts() { try { return getContactStore().getContacts().iterator(); } catch (Exception e) { LogUtil.logError(KeyStorePlugin.PLUGIN_ID, "Failed to retrieve contacts", e, true); } return null; } public int getContactSize() { LogUtil.logInfo("Contacts size is " + contactsDesc.size()); //$NON-NLS-1$ return contactsDesc.size(); } }
package org.jenerate.internal.domain.data.impl; import org.jenerate.internal.domain.data.EqualsHashCodeGenerationData; import org.jenerate.internal.domain.hashcode.IInitMultNumbers; public class EqualsHashCodeGenerationDataImpl extends AbstractMethodGenerationData implements EqualsHashCodeGenerationData { private final boolean compareReferences; private final IInitMultNumbers initMultNumbers; private final boolean classComparison; private EqualsHashCodeGenerationDataImpl(Builder builder) { super(builder); this.compareReferences = builder.builderCompareReferences; this.classComparison = builder.classComparison; this.initMultNumbers = builder.builderInitMultNumbers; } @Override public boolean getCompareReferences() { return compareReferences; } @Override public IInitMultNumbers getInitMultNumbers() { return initMultNumbers; } @Override public boolean getClassComparison() { return classComparison; } public static class Builder extends AbstractMethodGenerationData.Builder<Builder> { private boolean builderCompareReferences; private IInitMultNumbers builderInitMultNumbers; private boolean classComparison; @Override public Builder getThis() { return this; } public Builder withCompareReferences(boolean compareReferences) { this.builderCompareReferences = compareReferences; return getThis(); } public Builder withInitMultNumbers(IInitMultNumbers initMultNumbers) { this.builderInitMultNumbers = initMultNumbers; return getThis(); } public Builder withClassComparison(boolean classComparison) { this.classComparison = classComparison; return getThis(); } public EqualsHashCodeGenerationData build() { return new EqualsHashCodeGenerationDataImpl(getThis()); } } }
package com.planetmayo.debrief.satc_rcp.views; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Font; import java.awt.Frame; import java.awt.Panel; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimeZone; import javax.swing.JRootPane; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.beans.BeansObservables; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.ui.IActionBars; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.ui.Layer; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.TextAnchor; import org.jfree.util.ShapeUtilities; import org.swtchart.Chart; import org.swtchart.IAxis; import org.swtchart.IBarSeries; import org.swtchart.ISeries; import org.swtchart.ISeries.SeriesType; import com.planetmayo.debrief.satc.log.LogFactory; import com.planetmayo.debrief.satc.model.Precision; import com.planetmayo.debrief.satc.model.VehicleType; import com.planetmayo.debrief.satc.model.contributions.ATBForecastContribution; import com.planetmayo.debrief.satc.model.contributions.BaseContribution; import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution; import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution.BMeasurement; import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution.HostState; import com.planetmayo.debrief.satc.model.contributions.BearingMeasurementContribution.MDAResultsListener; import com.planetmayo.debrief.satc.model.contributions.CompositeStraightLegForecastContribution; import com.planetmayo.debrief.satc.model.contributions.ContributionBuilder; import com.planetmayo.debrief.satc.model.contributions.CourseForecastContribution; import com.planetmayo.debrief.satc.model.contributions.FrequencyMeasurementContribution; import com.planetmayo.debrief.satc.model.contributions.LocationForecastContribution; import com.planetmayo.debrief.satc.model.contributions.Range1959ForecastContribution; import com.planetmayo.debrief.satc.model.contributions.RangeForecastContribution; import com.planetmayo.debrief.satc.model.contributions.SpeedForecastContribution; import com.planetmayo.debrief.satc.model.contributions.StraightLegForecastContribution; import com.planetmayo.debrief.satc.model.generator.IBoundsManager; import com.planetmayo.debrief.satc.model.generator.IConstrainSpaceListener; import com.planetmayo.debrief.satc.model.generator.IContributions; import com.planetmayo.debrief.satc.model.generator.IContributionsChangedListener; import com.planetmayo.debrief.satc.model.generator.ISolver; import com.planetmayo.debrief.satc.model.generator.SteppingAdapter; import com.planetmayo.debrief.satc.model.generator.impl.ga.IGASolutionsListener; import com.planetmayo.debrief.satc.model.legs.CompositeRoute; import com.planetmayo.debrief.satc.model.legs.CoreRoute; import com.planetmayo.debrief.satc.model.manager.IContributionsManager; import com.planetmayo.debrief.satc.model.manager.ISolversManager; import com.planetmayo.debrief.satc.model.manager.ISolversManagerListener; import com.planetmayo.debrief.satc.model.manager.IVehicleTypesManager; import com.planetmayo.debrief.satc.model.states.BaseRange.IncompatibleStateException; import com.planetmayo.debrief.satc.model.states.State; import com.planetmayo.debrief.satc.util.GeoSupport; import com.planetmayo.debrief.satc.util.calculator.GeodeticCalculator; import com.planetmayo.debrief.satc.zigdetector.LegOfData; import com.planetmayo.debrief.satc_rcp.SATC_Activator; import com.planetmayo.debrief.satc_rcp.ui.UIListener; import com.planetmayo.debrief.satc_rcp.ui.UIUtils; import com.planetmayo.debrief.satc_rcp.ui.contributions.ATBForecastContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.BaseContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.BearingMeasurementContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.CompositeStraightLegForecastContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.CourseContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.FrequencyMeasurementContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.LocationForecastContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.RangeForecastContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.Ranging1959ContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.SpeedContributionView; import com.planetmayo.debrief.satc_rcp.ui.contributions.StraightLegForecastContributionView; import com.vividsolutions.jts.geom.Point; /** * mock class to test high level application flows * * @author ian * */ public class MaintainContributionsView extends ViewPart { private static final String PERFORMANCE_TITLE = "Overall score:"; private static final String TITLE = "Maintain Contributions"; private static final Map<Class<? extends BaseContribution>, Class<? extends BaseContributionView<?>>> CONTRIBUTION_PANELS; static { CONTRIBUTION_PANELS = new HashMap<Class<? extends BaseContribution>, Class<? extends BaseContributionView<?>>>(); CONTRIBUTION_PANELS.put(ATBForecastContribution.class, ATBForecastContributionView.class); CONTRIBUTION_PANELS.put(BearingMeasurementContribution.class, BearingMeasurementContributionView.class); CONTRIBUTION_PANELS.put(FrequencyMeasurementContribution.class, FrequencyMeasurementContributionView.class); CONTRIBUTION_PANELS.put(CourseForecastContribution.class, CourseContributionView.class); CONTRIBUTION_PANELS.put(LocationForecastContribution.class, LocationForecastContributionView.class); CONTRIBUTION_PANELS.put(Range1959ForecastContribution.class, Ranging1959ContributionView.class); CONTRIBUTION_PANELS.put(RangeForecastContribution.class, RangeForecastContributionView.class); CONTRIBUTION_PANELS.put(SpeedForecastContribution.class, SpeedContributionView.class); CONTRIBUTION_PANELS.put(CompositeStraightLegForecastContribution.class, CompositeStraightLegForecastContributionView.class); CONTRIBUTION_PANELS.put(StraightLegForecastContribution.class, StraightLegForecastContributionView.class); } /** UI fields */ private DataBindingContext context; private Composite main; private Button liveConstraints; private Button recalculate; private Button cancelGeneration; private Button suppressCuts; private Button showOSCourse; private ComboViewer precisionsCombo; // private ComboViewer vehiclesCombo; private Composite contList; // private Menu addContributionMenu; // private ToolItem addContributionButton; private transient HashMap<BaseContribution, Color> assignedColors; /** Contribution -> Contribution view mappings */ private HashMap<BaseContribution, BaseContributionView<?>> contributionsControl = new HashMap<BaseContribution, BaseContributionView<?>>(); private ISolver activeSolver; private ISolversManager solversManager; /** * current listeners */ private Binding liveRunningBinding; private IContributionsChangedListener contributionsChangedListener; private IGASolutionsListener generateSolutionsListener; private ISolversManagerListener solverManagerListener; private IConstrainSpaceListener constrainSpaceListener; private Chart performanceChart; private final java.awt.Color[] defaultColors = new java.awt.Color[] { java.awt.Color.red, java.awt.Color.green, java.awt.Color.yellow, java.awt.Color.blue, java.awt.Color.cyan, java.awt.Color.magenta, java.awt.Color.darkGray, java.awt.Color.orange, java.awt.Color.pink, java.awt.Color.lightGray }; private XYPlot legPlot; private PropertyChangeListener _legListener; private TabItem performanceTab; private TabItem legTab; private TabFolder graphTabs; private MDAResultsListener _sliceListener; private JFreeChart legChart; private Action _exportBtn; private Color _colorBlack; @Override public void createPartControl(final Composite parent) { context = new DataBindingContext(); IContributionsManager contributionsManager = SATC_Activator.getDefault() .getService(IContributionsManager.class, true); IVehicleTypesManager vehicleManager = SATC_Activator.getDefault() .getService(IVehicleTypesManager.class, true); solversManager = SATC_Activator.getDefault().getService( ISolversManager.class, true); initUI(parent); populateContributionList(contributionsManager.getAvailableContributions()); populatePrecisionsList(Precision.values()); populateVehicleTypesList(vehicleManager.getAllTypes()); initListeners(parent); solversManager.addSolversManagerListener(solverManagerListener); // also, set the help context PlatformUI.getWorkbench().getHelpSystem() .setHelp(parent, "org.mwc.debrief.help.SATC"); setActiveSolver(solversManager.getActiveSolver()); } @Override public void dispose() { context.dispose(); setActiveSolver(null); solversManager.removeSolverManagerListener(solverManagerListener); // ditch the colors if (assignedColors != null) { Iterator<Color> cIter = assignedColors.values().iterator(); while (cIter.hasNext()) { org.eclipse.swt.graphics.Color entry = cIter.next(); entry.dispose(); } assignedColors = null; } // and our SWT black shade if(!_colorBlack.isDisposed()) _colorBlack.dispose(); super.dispose(); } @Override public void setFocus() { } private void fillAnalystContributionsGroup(Composite parent) { GridLayout layout = new GridLayout(4, false); layout.marginHeight = 2; layout.marginWidth = 2; Composite header = UIUtils.createEmptyComposite(parent, layout, new GridData(GridData.FILL_HORIZONTAL)); UIUtils.createSpacer(header, new GridData(50, SWT.DEFAULT)); Composite headerNested = UIUtils.createEmptyComposite(header, UIUtils .createGridLayoutWithoutMargins(4, true), new GridData( GridData.FILL_HORIZONTAL)); UIUtils.createLabel(headerNested, SWT.CENTER, "Active", new GridData( GridData.FILL_HORIZONTAL)); UIUtils.createLabel(headerNested, SWT.CENTER, "Hard constraints", new GridData(GridData.FILL_HORIZONTAL)); UIUtils.createLabel(headerNested, SWT.CENTER, "Estimate", new GridData( GridData.FILL_HORIZONTAL)); UIUtils.createLabel(headerNested, SWT.CENTER, "Weighting", new GridData( GridData.HORIZONTAL_ALIGN_END)); UIUtils.createLabel(header, SWT.CENTER, "Delete", new GridData( GridData.HORIZONTAL_ALIGN_END)); UIUtils.createSpacer(header, new GridData(20, SWT.DEFAULT)); } private void initAddContributionGroup(Composite parent) { // GridData gridData = new GridData(); // gridData.horizontalAlignment = SWT.FILL; // gridData.grabExcessHorizontalSpace = true; // Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); // FillLayout fillLayout = new FillLayout(); // fillLayout.marginWidth = 5; // fillLayout.marginHeight = 5; // group.setLayout(fillLayout); // group.setLayoutData(gridData); // group.setText("New Contribution"); // addContributionMenu = new Menu(group); // final ToolBar toolBar = new ToolBar(group, SWT.NONE); // toolBar.setBounds(50, 50, 50, 50); // addContributionButton = new ToolItem(toolBar, SWT.DROP_DOWN); // addContributionButton.setText("Add..."); // addContributionButton.addListener(SWT.Selection, new Listener() // @Override // public void handleEvent(Event event) // if (event.detail == SWT.ARROW) // Rectangle rect = addContributionButton.getBounds(); // Point pt = new Point(rect.x, rect.y + rect.height); // pt = toolBar.toDisplay(pt); // addContributionMenu.setLocation(pt.x, pt.y); // addContributionMenu.setVisible(true); } private void initAnalystContributionsGroup(Composite parent) { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.verticalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.grabExcessVerticalSpace = true; Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); group.setLayout(new GridLayout(1, false)); group.setLayoutData(gridData); group.setText("Analyst Contributions"); fillAnalystContributionsGroup(group); final ScrolledComposite scrolled = new ScrolledComposite(group, SWT.V_SCROLL | SWT.H_SCROLL); scrolled.setLayoutData(new GridData(GridData.FILL_BOTH)); contList = UIUtils.createScrolledBody(scrolled, SWT.NONE); contList.setLayout(new GridLayout(1, false)); scrolled.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event e) { scrolled.setMinSize(contList.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } }); scrolled.setAlwaysShowScrollBars(true); scrolled.setContent(contList); scrolled.setMinSize(contList.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolled.setExpandHorizontal(true); scrolled.setExpandVertical(true); } private void initPreferencesGroup(Composite parent) { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); GridLayout layout = new GridLayout(1, false); group.setLayoutData(gridData); group.setLayout(layout); group.setText("Preferences"); final ScrolledComposite scrolled = new ScrolledComposite(group, SWT.H_SCROLL); scrolled.setLayoutData(new GridData(GridData.FILL_BOTH)); final Composite preferencesComposite = UIUtils.createScrolledBody(scrolled, SWT.NONE); preferencesComposite.setLayout(new GridLayout(6, false)); scrolled.addListener(SWT.Resize, new Listener() { @Override public void handleEvent(Event e) { scrolled.setMinSize(preferencesComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } }); scrolled.setAlwaysShowScrollBars(true); scrolled.setContent(preferencesComposite); scrolled.setMinSize(preferencesComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT)); scrolled.setExpandHorizontal(true); scrolled.setExpandVertical(true); liveConstraints = new Button(preferencesComposite, SWT.TOGGLE); liveConstraints.setText("Auto-Recalc of Constraints"); liveConstraints.setEnabled(false); liveConstraints.setLayoutData(new GridData( GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER)); recalculate = new Button(preferencesComposite, SWT.DEFAULT); recalculate.setText("Calculate Solution"); recalculate.setEnabled(false); recalculate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (activeSolver != null) { // ok - make sure the performance tab is open graphTabs.setSelection(performanceTab); activeSolver.run(true, true); main.setSize(0, 0); main.getParent().layout(true, true); } } }); recalculate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER | GridData.VERTICAL_ALIGN_CENTER)); cancelGeneration = new Button(preferencesComposite, SWT.PUSH); cancelGeneration.setText("Cancel"); cancelGeneration.setVisible(false); cancelGeneration.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (activeSolver != null) { activeSolver.cancel(); } } }); suppressCuts = new Button(preferencesComposite, SWT.CHECK); suppressCuts.setText("Suppress Cuts"); suppressCuts.setVisible(true); suppressCuts.setEnabled(false); suppressCuts.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (activeSolver != null) { boolean doSuppress = suppressCuts.getSelection(); activeSolver.setAutoSuppress(doSuppress); } } }); showOSCourse = new Button(preferencesComposite, SWT.CHECK); showOSCourse.setText("Plot O/S Course"); showOSCourse.setVisible(true); showOSCourse.setEnabled(false); showOSCourse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (activeSolver != null) { redoOwnshipStates(); } } }); Composite precisionPanel = new Composite(preferencesComposite, SWT.NONE); precisionPanel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_CENTER)); GridLayout precisionLayout = new GridLayout(2, false); precisionLayout.horizontalSpacing = 5; precisionPanel.setLayout(precisionLayout); Label precisionLabel = new Label(precisionPanel, SWT.NONE); precisionLabel.setText("Precision:"); precisionLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_CENTER)); precisionsCombo = new ComboViewer(precisionPanel); precisionsCombo.getCombo().setEnabled(false); precisionsCombo.setContentProvider(new ArrayContentProvider()); precisionsCombo.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { return ((Precision) element).getLabel(); } }); precisionsCombo.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ISelection sel = precisionsCombo.getSelection(); IStructuredSelection cSel = (IStructuredSelection) sel; Precision precision = (Precision) cSel.getFirstElement(); if (activeSolver != null) { activeSolver.setPrecision(precision); } } }); } private void initUI(final Composite parent) { parent.setLayout(new FillLayout()); final SashForm sashForm = new SashForm(parent, SWT.VERTICAL); sashForm.SASH_WIDTH = 15; sashForm.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY)); main = new Composite(sashForm, SWT.NONE); GridLayout gridLayout = new GridLayout(1, true); gridLayout.verticalSpacing = 2; gridLayout.marginLeft = 5; gridLayout.marginRight = 5; main.setLayout(gridLayout); initPreferencesGroup(main); initVehicleGroup(main); initAnalystContributionsGroup(main); initAddContributionGroup(main); Composite lowerSection = new Composite(sashForm, SWT.NONE); lowerSection.setLayout(new FillLayout()); // ok - the next section needs to be in a sash - so we can resize it initGraphTabs(lowerSection); // set the relative sizes in the sash sashForm.setWeights(new int[] { 3, 1 }); // also sort out the header controls final IActionBars bars = getViewSite().getActionBars(); IToolBarManager manager = bars.getToolBarManager(); manager.add(SATC_Activator.createOpenHelpAction( "org.mwc.debrief.help.SATC", null, this)); _exportBtn = new Action("Export SATC dataset", Action.AS_PUSH_BUTTON) { public void runWithEvent(final Event event) { exportSATC(); } }; _exportBtn.setToolTipText("Export SATC scenario to clipboard"); _exportBtn.setImageDescriptor(SATC_Activator .getImageDescriptor("icons/export.png")); manager.add(_exportBtn); } private void initGraphTabs(Composite parent) { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.heightHint = 200; graphTabs = new TabFolder(parent, SWT.BORDER); FillLayout fillLayout = new FillLayout(); fillLayout.marginWidth = 5; fillLayout.marginHeight = 5; // tabs.setLayout(fillLayout); graphTabs.setLayoutData(gridData); legTab = new TabItem(graphTabs, SWT.NONE); legTab.setText("Target Legs"); Composite perfG1 = initLegGraph(graphTabs); legTab.setControl(perfG1); performanceTab = new TabItem(graphTabs, SWT.NONE); performanceTab.setText("Performance"); Group perfG2 = initPerformanceGraph(graphTabs); performanceTab.setControl(perfG2); } private Group initPerformanceGraph(Composite parent) { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = true; gridData.heightHint = 200; Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); FillLayout fillLayout = new FillLayout(); fillLayout.marginWidth = 5; fillLayout.marginHeight = 5; group.setLayout(fillLayout); group.setLayoutData(gridData); // group.setText("Performance"); // we need the color black several times _colorBlack = new Color(Display.getCurrent(), 0, 0, 0); // generate the chart performanceChart = new Chart(group, SWT.NONE); // format the chart performanceChart.getLegend().setVisible(false); performanceChart.getTitle().setVisible(true); performanceChart.setForeground(_colorBlack); performanceChart.getTitle().setText(PERFORMANCE_TITLE + " Pending"); performanceChart.getTitle().setForeground(_colorBlack); // now give the chart our data series // ok, now for the x axis IAxis xAxis = performanceChart.getAxisSet().getXAxis(0); xAxis.getTitle().setVisible(false); xAxis.adjustRange(); xAxis.getTick().setForeground(_colorBlack); // and the y axis IAxis yAxis = performanceChart.getAxisSet().getYAxis(0); yAxis.adjustRange(); yAxis.enableLogScale(true); yAxis.getTick().setForeground(_colorBlack); yAxis.getTitle().setForeground(_colorBlack); yAxis.getTitle().setText("Weighted error"); return group; } /** * This is a callback that will allow us to create the viewer and initialize * it. */ public Composite initLegGraph(final Composite parent) { // right, we need an SWT.EMBEDDED object to act as a holder final Composite holder = new Composite(parent, SWT.NO_BACKGROUND | SWT.EMBEDDED | SWT.NO_REDRAW_RESIZE); holder.setLayoutData(new GridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL)); /* * Set a Windows specific AWT property that prevents heavyweight components * from erasing their background. Note that this is a global property and * cannot be scoped. It might not be suitable for your application. */ try { System.setProperty("sun.awt.noerasebackground", "true"); } catch (NoSuchMethodError error) { } // java.awt.Toolkit.getDefaultToolkit().setDynamicLayout(false); // now we need a Swing object to put our chart into /* Create and setting up frame */ Frame frame = SWT_AWT.new_Frame(holder); Panel panel = new Panel(new BorderLayout()) { private static final long serialVersionUID = 1L; @Override public void update(java.awt.Graphics g) { /* Do not erase the background */ paint(g); } }; frame.add(panel); JRootPane root = new JRootPane(); root.setDoubleBuffered(true); panel.add(root); Container _legPane = root.getContentPane(); legChart = ChartFactory.createTimeSeriesChart("Target Legs", // String "Time", // String timeAxisLabel null, // String valueAxisLabel, null, // XYDataset dataset, true, // include legend true, // tooltips false); // urls legPlot = (XYPlot) legChart.getPlot(); legPlot.setDomainCrosshairVisible(true); legPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) legPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); legPlot.setBackgroundPaint(java.awt.Color.WHITE); legPlot.setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY); legPlot.setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY); // format the cross hairs, when they're clicked legPlot.setDomainCrosshairVisible(true); legPlot.setRangeCrosshairVisible(true); legPlot.setDomainCrosshairPaint(java.awt.Color.GRAY); legPlot.setRangeCrosshairPaint(java.awt.Color.GRAY); legPlot.setDomainCrosshairStroke(new BasicStroke(1)); legPlot.setRangeCrosshairStroke(new BasicStroke(1)); // and the plot object to display the cross hair value final XYTextAnnotation annot = new XYTextAnnotation(" annot.setTextAnchor(TextAnchor.TOP_LEFT); annot.setPaint(java.awt.Color.black); annot.setBackgroundPaint(java.awt.Color.white); legPlot.addAnnotation(annot); legChart.addProgressListener(new ChartProgressListener() { public void chartProgress(final ChartProgressEvent cpe) { if (cpe.getType() != ChartProgressEvent.DRAWING_FINISHED) return; // double-check our label is still in the right place final double xVal = legPlot.getRangeAxis().getUpperBound(); final double yVal = legPlot.getDomainAxis().getLowerBound(); boolean annotChanged = false; if (annot.getX() != yVal) { annot.setX(yVal); annotChanged = true; } if (annot.getY() != xVal) { annot.setY(xVal); annotChanged = true; } // and write the text final String numA = MWC.Utilities.TextFormatting.GeneralFormat .formatOneDecimalPlace(legPlot.getRangeCrosshairValue()); final Date newDate = new Date((long) legPlot.getDomainCrosshairValue()); final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss"); _df.setTimeZone(TimeZone.getTimeZone("GMT")); final String dateVal = _df.format(newDate); final String theMessage = " [" + dateVal + "," + numA + "]"; if (!theMessage.equals(annot.getText())) { annot.setText(theMessage); annotChanged = true; } // aah, now we have to add and then remove the annotation in order // for the new text value to be displayed. Watch and learn... if (annotChanged) { legPlot.removeAnnotation(annot); legPlot.addAnnotation(annot); } } }); ChartPanel chartInPanel = new ChartPanel(legChart, true); // // ok - we need to fire time-changes to the chart // setupFiringChangesToChart(); // format the chart chartInPanel.setName("Legs"); chartInPanel.setMouseZoomable(true, true); // and insert into the panel _legPane.add(chartInPanel, BorderLayout.CENTER); return holder; } /** * clear the data on the leg graph * */ private void clearLegGraph() { if (legPlot == null) return; legPlot.setDataset(0, null); legPlot.setDataset(1, null); legPlot.setDataset(2, null); legPlot.setDataset(3, null); legPlot.clearDomainMarkers(); } private void clearPerformanceGraph() { // hmm, have we already ditched? if (performanceChart.isDisposed()) return; ISeries[] sets = performanceChart.getSeriesSet().getSeries(); for (int i = 0; i < sets.length; i++) { ISeries iSeries = sets[i]; performanceChart.getSeriesSet().deleteSeries(iSeries.getId()); } // ySeries.setYSeries(newYVals); performanceChart.getAxisSet().getXAxis(0).adjustRange(); performanceChart.getAxisSet().getYAxis(0).adjustRange(); performanceChart.getAxisSet().getYAxis(0).enableLogScale(true); performanceChart.redraw(); } private Color colorFor(BaseContribution contribution) { if (assignedColors == null) { assignedColors = new HashMap<BaseContribution, Color>(); } // have we already assigned this one? Color res = assignedColors.get(contribution); if (res == null) { int index = assignedColors.size() % defaultColors.length; java.awt.Color newCol = defaultColors[index]; res = new Color(Display.getDefault(), newCol.getRed(), newCol.getGreen(), newCol.getBlue()); assignedColors.put(contribution, res); } return res; } private void addNewPerformanceScore(double value, List<CompositeRoute> topRoutes) { // remember each contribution's set of scores HashMap<BaseContribution, HashMap<Date, Double>> stackedSeries = new HashMap<BaseContribution, HashMap<Date, Double>>(); // remember the times for which we have states ArrayList<Date> valueTimes = new ArrayList<Date>(); // ok - have a look at the scores Iterator<CoreRoute> legIter = topRoutes.get(0).getLegs().iterator(); while (legIter.hasNext()) { CoreRoute route = legIter.next(); Iterator<State> states = route.getStates().iterator(); while (states.hasNext()) { State state = states.next(); HashMap<BaseContribution, Double> scores = state.getScores(); Iterator<BaseContribution> contributions = scores.keySet().iterator(); while (contributions.hasNext()) { BaseContribution cont = contributions.next(); // get the score Double score = scores.get(cont); if (score > 0) { HashMap<Date, Double> thisSeries = stackedSeries.get(cont); if (thisSeries == null) { thisSeries = new HashMap<Date, Double>(); stackedSeries.put(cont, thisSeries); final IBarSeries series = (IBarSeries) performanceChart .getSeriesSet().createSeries(SeriesType.BAR, cont.getName()); series.setBarColor(colorFor(cont)); // series.enableStack(true); } thisSeries.put(state.getTime(), scores.get(cont)); // store the time of this value if (!valueTimes.contains(state.getTime())) { valueTimes.add(state.getTime()); } } } } } // ok, now loop through the series Iterator<BaseContribution> conts = stackedSeries.keySet().iterator(); while (conts.hasNext()) { BaseContribution cont = conts.next(); HashMap<Date, Double> vals = stackedSeries.get(cont); if (vals.size() > 0) { final IBarSeries series = (IBarSeries) performanceChart.getSeriesSet() .getSeries(cont.getName()); // ok, we need to produce a value for each value time double[] valArr = new double[valueTimes.size()]; Iterator<Date> iter2 = valueTimes.iterator(); int ctr = 0; while (iter2.hasNext()) { Date date = iter2.next(); Double thisV = vals.get(date); final double res; if (thisV != null) res = thisV; else res = 0; valArr[ctr++] = res; } series.setYSeries(valArr); // series.enableStack(true); } } // prepare the category labels String[] labels = new String[valueTimes.size()]; Iterator<Date> vIter = valueTimes.iterator(); // get our date formatter ready SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // determine frequency f (trim to 1) int wid = performanceChart.getBounds().width; int allowed = wid / 90; int freq = Math.max(labels.length / allowed, 1); int ctr = 0; while (vIter.hasNext()) { Date date = vIter.next(); final String str; if (ctr % freq == 0) str = sdf.format(date); else str = ""; labels[ctr++] = str; } // set category labels performanceChart.getAxisSet().getXAxis(0).enableCategory(true); performanceChart.getAxisSet().getXAxis(0).setCategorySeries(labels); ISeries[] series = performanceChart.getSeriesSet().getSeries(); if (series.length == 2 && series[0] instanceof IBarSeries && series[1] instanceof IBarSeries) { performanceChart.getLegend().setVisible(true); performanceChart.getLegend().setPosition(SWT.RIGHT); IBarSeries barSeries1 = (IBarSeries) series[0]; IBarSeries barSeries2 = (IBarSeries) series[1]; // enable stack series barSeries1.enableStack(false); barSeries2.enableStack(false); barSeries1.enableStack(true); barSeries2.enableStack(true); } // and resize the axes performanceChart.getAxisSet().adjustRange(); performanceChart.getTitle().setText(PERFORMANCE_TITLE +(int)value); performanceChart.redraw(); } private void initVehicleGroup(Composite parent) { // GridData gridData = new GridData(); // gridData.horizontalAlignment = SWT.FILL; // gridData.grabExcessHorizontalSpace = true; // Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); // FillLayout fillLayout = new FillLayout(); // fillLayout.marginWidth = 5; // fillLayout.marginHeight = 5; // group.setLayout(fillLayout); // group.setLayoutData(gridData); // group.setText("Vehicle"); // vehiclesCombo = new ComboViewer(group); // vehiclesCombo.setContentProvider(new ArrayContentProvider()); // vehiclesCombo.setLabelProvider(new LabelProvider() // @Override // public String getText(Object element) // return ((VehicleType) element).getName(); // vehiclesCombo.addSelectionChangedListener(new // ISelectionChangedListener() // @Override // public void selectionChanged(SelectionChangedEvent event) // if (activeSolver != null) // ISelection selection = event.getSelection(); // if (selection instanceof StructuredSelection) // VehicleType type = // (VehicleType) ((StructuredSelection) selection) // .getFirstElement(); // activeSolver.setVehicleType(type); } public void populateContributionList(List<ContributionBuilder> items) { // for (final ContributionBuilder item : items) // MenuItem menuItem = new MenuItem(addContributionMenu, SWT.PUSH); // menuItem.setText(item.getDescription()); // menuItem.addSelectionListener(new SelectionAdapter() // @Override // public void widgetSelected(SelectionEvent arg0) // if (activeSolver != null) // activeSolver.getContributions().addContribution(item.create()); } public void populatePrecisionsList(Precision[] precisions) { precisionsCombo.setInput(precisions); precisionsCombo.setSelection(new StructuredSelection(precisions[0])); } public void populateVehicleTypesList(List<VehicleType> vehicles) { // vehiclesCombo.setInput(vehicles); // // ok, try to set the first one // if (vehicles.size() > 0) // vehiclesCombo.setSelection(new // StructuredSelection(vehicles.iterator() // .next())); } private void initListeners(final Composite parent) { contributionsChangedListener = UIListener.wrap(parent.getDisplay(), IContributionsChangedListener.class, new IContributionsChangedListener() { @Override public void removed(BaseContribution contribution) { removeContribution(contribution, true); } @Override public void added(BaseContribution contribution) { addContribution(contribution, true); } @Override public void modified() { } }); generateSolutionsListener = UIListener.wrap(parent.getDisplay(), IGASolutionsListener.class, new SteppingAdapter() { Control focused = null; @Override public void startingGeneration() { focused = parent.getDisplay().getFocusControl(); UIUtils.setEnabled(parent, false); cancelGeneration.setVisible(true); cancelGeneration.setEnabled(true); // ok, clear the graph clearPerformanceGraph(); } @Override public void iterationComputed(List<CompositeRoute> topRoutes, double topScore) { addNewPerformanceScore(topScore, topRoutes); } @Override public void finishedGeneration(Throwable error) { UIUtils.setEnabled(parent, true); cancelGeneration.setVisible(false); // we've encountered an instance during file-load where // focused // null, better check it if (focused != null) focused.setFocus(); } }); solverManagerListener = UIListener.wrap(parent.getDisplay(), ISolversManagerListener.class, new ISolversManagerListener() { @Override public void solverCreated(final ISolver solver) { } @Override public void activeSolverChanged(final ISolver activeSolver) { setActiveSolver(activeSolver); } }); constrainSpaceListener = UIListener.wrap(parent.getDisplay(), IConstrainSpaceListener.class, new IConstrainSpaceListener() { @Override public void stepped(IBoundsManager boundsManager, int thisStep, int totalSteps) { } @Override public void statesBounded(IBoundsManager boundsManager) { // minimum steps to get the contributions list to redraw contList.setSize(0, 0); } @Override public void restarted(IBoundsManager boundsManager) { } @Override public void error(IBoundsManager boundsManager, IncompatibleStateException ex) { } }); } public void setActiveSolver(final ISolver solver) { // just double check that we aren't already looking at this solver if (solver != activeSolver) { // clear the charts - just in case clearPerformanceGraph(); clearLegGraph(); // other UI mgt if (activeSolver != null) { activeSolver.getContributions().removeContributionsChangedListener( contributionsChangedListener); activeSolver.getSolutionGenerator().removeReadyListener( generateSolutionsListener); activeSolver.getBoundsManager().removeConstrainSpaceListener( constrainSpaceListener); liveRunningBinding.dispose(); } List<BaseContribution> contributions = new ArrayList<BaseContribution>( contributionsControl.keySet()); for (BaseContribution contribution : contributions) { removeContribution(contribution, false); } if (!contList.isDisposed()) { contList.layout(); } activeSolver = solver; boolean hasSolver = activeSolver != null; if (hasSolver) { activeSolver.getContributions().addContributionsChangedListener( contributionsChangedListener); activeSolver.getSolutionGenerator().addReadyListener( generateSolutionsListener); activeSolver.getBoundsManager().addConstrainSpaceListener( constrainSpaceListener); for (BaseContribution contribution : activeSolver.getContributions()) { addContribution(contribution, false); } contList.layout(); // vehiclesCombo.setSelection(new // StructuredSelection(activeSolver // .getVehicleType())); precisionsCombo.setSelection(new StructuredSelection(activeSolver .getPrecision())); suppressCuts.setSelection(activeSolver.getAutoSuppress()); liveRunningBinding = context.bindValue(WidgetProperties.selection() .observe(liveConstraints), BeansObservables.observeValue( activeSolver, ISolver.LIVE_RUNNING)); setPartName(TITLE + " - " + activeSolver.getName()); } else { setPartName(TITLE); } if (!contList.isDisposed()) { precisionsCombo.getCombo().setEnabled(hasSolver); liveConstraints.setEnabled(hasSolver); recalculate.setEnabled(hasSolver); performanceChart.setEnabled(hasSolver); suppressCuts.setEnabled(hasSolver); showOSCourse.setEnabled(hasSolver); // vehiclesCombo.getCombo().setEnabled(hasSolver); // addContributionButton.setEnabled(hasSolver); } } } public void addContribution(BaseContribution contribution, boolean doLayout) { // ok, create a wrapper for this BaseContributionView<?> panel = null; if (!CONTRIBUTION_PANELS.containsKey(contribution.getClass())) { return; } try { Class<?> viewClass = CONTRIBUTION_PANELS.get(contribution.getClass()); panel = (BaseContributionView<?>) viewClass.getConstructor( Composite.class, contribution.getClass(), IContributions.class) .newInstance(contList, contribution, activeSolver.getContributions()); panel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); // see if we can give it a default color panel.setDefaultColor(colorFor(contribution)); // now store it contributionsControl.put(contribution, panel); if (doLayout) { contList.layout(); } // hmm, is this a new straight leg? if (contribution instanceof StraightLegForecastContribution) { // ok - listen out for period changes StraightLegForecastContribution slf = (StraightLegForecastContribution) contribution; if (_legListener == null) _legListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { redoStraightLegs(); } }; startListeningTo(slf); // ok - chuck in a graph update redoStraightLegs(); } else if (contribution instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) contribution; if (_sliceListener == null) { _sliceListener = new BearingMeasurementContribution.MDAResultsListener() { @Override public void startingSlice(String contName) { // ok - ownship course is important for this - show it showOSCourse.setSelection(true); startSlicingOwnshipLegs(contName); } @Override public void ownshipLegs(String contName, ArrayList<BMeasurement> bearings, List<LegOfData> ownshipLegs, ArrayList<HostState> hostStates) { // clear the domain markers, this is a new dataset legPlot.clearDomainMarkers(); // and show the ownship states redoOwnshipStates(); } @Override public void sliced(String contName, ArrayList<StraightLegForecastContribution> arrayList) { // are we currently showing ownship course? if(showOSCourse.getSelection()) { // ok, ownship course is irrelevant to this, hide it showOSCourse.setSelection(false); // update the ownship states, now that we've hidden the O/S course redoOwnshipStates(); } // ok, now display the target legs redoStraightLegs(); } }; } bmc.addSliceListener(_sliceListener); // hey, let's also re-display the ownship states redoOwnshipStates(); } } catch (Exception ex) { LogFactory.getLog().error("Failed to generate panel for " + contribution); SATC_Activator .getDefault() .getLog() .log( new Status(IStatus.ERROR, SATC_Activator.PLUGIN_ID, ex .getMessage(), ex)); } } protected void startSlicingOwnshipLegs(String contName) { // hey, let's also ditch any straight leg forecasts Iterator<BaseContribution> conts = activeSolver.getContributions() .iterator(); ArrayList<BaseContribution> toRemove = new ArrayList<BaseContribution>(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof StraightLegForecastContribution) { toRemove.add(baseC); } } // did we find any? if (!toRemove.isEmpty()) { Iterator<BaseContribution> iter = toRemove.iterator(); while (iter.hasNext()) { BaseContribution baseContribution = iter.next(); activeSolver.getContributions().removeContribution(baseContribution); } } // ok, clear any leg markers if (legPlot != null) { graphTabs.setSelection(legTab); legPlot.clearDomainMarkers(); } } protected void redoOwnshipStates() { if (legPlot == null) return; boolean showCourses = true; if (showOSCourse != null) showCourses = showOSCourse.getSelection(); java.awt.Color courseCol = java.awt.Color.blue.darker().darker(); java.awt.Color speedCol = java.awt.Color.blue.brighter().brighter(); // ok, now loop through and set them long startTime = Long.MAX_VALUE; long endTime = Long.MIN_VALUE; // clear any datasets legPlot.setDataset(0, null); legPlot.setDataset(1, null); // hmm, actually we have to remove any target leg markers @SuppressWarnings("unchecked") Collection<IntervalMarker> markers = legPlot .getDomainMarkers(Layer.BACKGROUND); if (markers != null) { ArrayList<IntervalMarker> markersToDelete = new ArrayList<IntervalMarker>( markers); Iterator<IntervalMarker> mIter = markersToDelete.iterator(); while (mIter.hasNext()) { IntervalMarker im = mIter.next(); legPlot.removeDomainMarker(im); } } // hey, does it have any ownship legs? TimeSeriesCollection tscC = new TimeSeriesCollection(); TimeSeriesCollection tscS = new TimeSeriesCollection(); TimeSeriesCollection tscCLegs = new TimeSeriesCollection(); TimeSeriesCollection tscSLegs = new TimeSeriesCollection(); TimeSeries courses = new TimeSeries("Course"); TimeSeries bearings = new TimeSeries("Bearings"); TimeSeries speeds = new TimeSeries("Speed"); TimeSeries courseLegs = new TimeSeries("Course (leg)"); TimeSeries speedLegs = new TimeSeries("Speed (leg)"); Iterator<BaseContribution> conts = activeSolver.getContributions() .iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; LegOfData thisLeg = null; if (bmc.getOwnshipLegs() != null) { lIter = bmc.getOwnshipLegs().iterator(); thisLeg = lIter.next(); } List<HostState> hostStates = bmc.getHostState(); if (hostStates != null) { Iterator<HostState> stateIter = hostStates.iterator(); while (stateIter.hasNext()) { BearingMeasurementContribution.HostState hostState = stateIter .next(); long thisTime = hostState.time; double thisCourse = hostState.courseDegs; if (showCourses) courses.add(new FixedMillisecond(thisTime), thisCourse); double thisSpeed = hostState.speedKts; speeds.add(new FixedMillisecond(thisTime), thisSpeed); startTime = Math.min(thisTime, startTime); endTime = Math.max(thisTime, endTime); // sort out if this is in a leg or not if (thisLeg != null) { if (thisTime > thisLeg.getEnd() && lIter.hasNext()) { thisLeg = lIter.next(); } else { if (thisTime >= thisLeg.getStart()) { speedLegs.add(new FixedMillisecond(thisTime), thisSpeed); if (showCourses) courseLegs .add(new FixedMillisecond(thisTime), thisCourse); } } } } } // also, we wish to show the bearings from the BMC Iterator<BMeasurement> cuts = bmc.getMeasurements().iterator(); while (cuts.hasNext()) { BearingMeasurementContribution.BMeasurement measurement = cuts .next(); if (measurement.isActive()) { long thisT = measurement.getDate().getTime(); bearings.add(new FixedMillisecond(thisT), Math.toDegrees(Math.abs(measurement.getBearingRads()))); } } } } // HEY, also shade the ownship legs conts = activeSolver.getContributions().iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) { if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; Iterator<LegOfData> lIter = null; if (bmc.getOwnshipLegs() != null) { int ctr = 1; lIter = bmc.getOwnshipLegs().iterator(); while (lIter.hasNext()) { LegOfData thisL = lIter.next(); long thisStart = thisL.getStart(); long thisFinish = thisL.getEnd(); java.awt.Color transCol = new java.awt.Color(0, 0, 255, 12); final Marker bst = new IntervalMarker(thisStart, thisFinish, transCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel("O/S-" + ctr++); bst.setLabelAnchor(RectangleAnchor.TOP_LEFT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.TOP_LEFT); legPlot.addDomainMarker(bst, Layer.BACKGROUND); } } } } } tscS.addSeries(speeds); tscSLegs.addSeries(speedLegs); tscC.addSeries(bearings); if (showCourses) { tscC.addSeries(courses); tscCLegs.addSeries(courseLegs); } legPlot.setDataset(0, null); legPlot.setDataset(1, null); legPlot.setDataset(2, null); legPlot.setDataset(3, null); legPlot.setDataset(0, tscC); legPlot.setDataset(1, tscS); legPlot.setDataset(2, tscCLegs); legPlot.setDataset(3, tscSLegs); final NumberAxis axis2 = new NumberAxis("Speed (Kts)"); legPlot.setRangeAxis(1, axis2); legPlot.mapDatasetToRangeAxis(1, 1); legPlot.mapDatasetToRangeAxis(3, 1); legPlot.getRangeAxis(0).setLabel("Crse/Brg (Degs)"); legPlot.mapDatasetToRangeAxis(0, 0); legPlot.mapDatasetToRangeAxis(2, 0); final XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer( true, true); lineRenderer1.setSeriesPaint(1, courseCol); lineRenderer1.setSeriesShape(1, ShapeUtilities.createDiamond(0.1f)); lineRenderer1.setSeriesPaint(0, java.awt.Color.RED); lineRenderer1.setSeriesShape(0, ShapeUtilities.createDiamond(2f)); final XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer( true, false); lineRenderer2.setSeriesPaint(0, speedCol); final XYLineAndShapeRenderer lineRenderer3 = new XYLineAndShapeRenderer( false, true); lineRenderer3.setSeriesPaint(0, courseCol); lineRenderer3.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f)); final XYLineAndShapeRenderer lineRenderer4 = new XYLineAndShapeRenderer( false, true); lineRenderer4.setSeriesPaint(0, speedCol); lineRenderer4.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f)); // ok, and store them legPlot.setRenderer(0, lineRenderer1); legPlot.setRenderer(1, lineRenderer2); legPlot.setRenderer(2, lineRenderer3); legPlot.setRenderer(3, lineRenderer4); if(startTime != Long.MAX_VALUE) legPlot.getDomainAxis().setRange(startTime, endTime); // ok - get the straight legs to sort themselves out // redoStraightLegs(); } protected void redoStraightLegs() { // ok, clear any leg markers if (legPlot != null) { if (!graphTabs.isDisposed()) graphTabs.setSelection(legTab); // hmm, actually we have to remove any target leg markers @SuppressWarnings("unchecked") Collection<IntervalMarker> markers = legPlot .getDomainMarkers(Layer.FOREGROUND); if (markers != null) { ArrayList<IntervalMarker> markersToDelete = new ArrayList<IntervalMarker>( markers); Iterator<IntervalMarker> mIter = markersToDelete.iterator(); while (mIter.hasNext()) { IntervalMarker im = mIter.next(); legPlot.removeDomainMarker(im); } } Iterator<BaseContribution> conts = activeSolver.getContributions() .iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC.isActive()) if (baseC instanceof StraightLegForecastContribution) { StraightLegForecastContribution slf = (StraightLegForecastContribution) baseC; java.awt.Color thisCol = slf.getColor(); // hmm, has it been given a color (initialised) yet? if (thisCol == null) continue; long thisStart = baseC.getStartDate().getTime(); long thisFinish = baseC.getFinishDate().getTime(); java.awt.Color transCol = new java.awt.Color(255, 0, 0, 22); final Marker bst = new IntervalMarker(thisStart, thisFinish, transCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel(baseC.getName()); bst.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_LEFT); legPlot.addDomainMarker(bst, Layer.FOREGROUND); } else { if (baseC instanceof BearingMeasurementContribution) { } } } } } protected void removeContribution(BaseContribution contribution, boolean doLayout) { BaseContributionView<?> panel = contributionsControl.get(contribution); if (panel != null) { panel.dispose(); contributionsControl.remove(contribution); if (doLayout) { contList.layout(); } } // aaah, is it a straight leg? if (contribution instanceof StraightLegForecastContribution) { stopListeningTo(contribution); // ok, better update the legs too. AAh, not if the form is closing if (doLayout) { redoStraightLegs(); } } else if (contribution instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) contribution; bmc.removeSliceListener(_sliceListener); } } @Override protected void finalize() throws Throwable { // clear our listeners Iterator<BaseContribution> conts = activeSolver.getContributions() .iterator(); while (conts.hasNext()) { BaseContribution contribution = conts.next(); // aaah, is it a straight leg? if (contribution instanceof StraightLegForecastContribution) { stopListeningTo(contribution); } else if (contribution instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) contribution; bmc.removeSliceListener(_sliceListener); } } // let the parent shut down super.finalize(); } private void startListeningTo(final StraightLegForecastContribution slf) { slf.addPropertyChangeListener(BaseContribution.START_DATE, _legListener); slf.addPropertyChangeListener(BaseContribution.FINISH_DATE, _legListener); slf.addPropertyChangeListener(BaseContribution.NAME, _legListener); slf.addPropertyChangeListener(BaseContribution.ACTIVE, _legListener); } private void stopListeningTo(final BaseContribution slf) { slf.removePropertyChangeListener(BaseContribution.ACTIVE, _legListener); slf.removePropertyChangeListener(BaseContribution.START_DATE, _legListener); slf.removePropertyChangeListener(BaseContribution.FINISH_DATE, _legListener); slf.removePropertyChangeListener(BaseContribution.NAME, _legListener); } /** * copy the SATC scenario to the clipboard * */ protected void exportSATC() { // - ok, really we just export the state & bearing data if (activeSolver != null) { StringBuffer res = new StringBuffer(); final String newLine = System.getProperty("line.separator"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); @SuppressWarnings("deprecation") Date dateLead = new Date(100, 7, 7); Iterator<BaseContribution> conts = activeSolver.getContributions() .iterator(); while (conts.hasNext()) { BaseContribution baseC = conts.next(); if (baseC instanceof BearingMeasurementContribution) { BearingMeasurementContribution bmc = (BearingMeasurementContribution) baseC; // ok - sort out the date offset Date startDate = bmc.getStartDate(); long offset = startDate.getTime() - dateLead.getTime(); // get ready for the offset Point2D origin = null; // get ready to calculate offsetes GeodeticCalculator calc = GeoSupport.createCalculator(); // ok, first the states res.append("//X, Y, Time, Course Degs, Speed Kts" + newLine); Iterator<HostState> states = bmc.getHostState().iterator(); while (states.hasNext()) { BearingMeasurementContribution.HostState hostState = states.next(); // sort out the X,Y offset double x,y; if(origin == null) { x = 0; y = 0; origin = new Point2D.Double(hostState.point.getX(), hostState.point.getY()); } else { // ok, calc a new XY, from the origin java.awt.geom.Point2D.Double thisP = new Point2D.Double(hostState.point.getX(), hostState.point.getY()); calc.setStartingGeographicPoint(origin); calc.setDestinationGeographicPoint(thisP); double angle = calc.getAzimuth(); double dist = calc.getOrthodromicDistance(); // and the new x,y coords x = Math.sin(Math.toRadians(angle)) * dist; y = Math.cos(Math.toRadians(angle)) * dist; } res.append(x + ", " + y + ", " + sdf.format(new Date(hostState.time - offset)) + "," + hostState.courseDegs + "," + hostState.speedKts + newLine); } // now the cuts res.append("//Time, Bearing Degs" + newLine); Iterator<BMeasurement> cuts = bmc.getMeasurements().iterator(); while (cuts.hasNext()) { BearingMeasurementContribution.BMeasurement cut = cuts.next(); res.append(sdf.format(new Date(cut.getDate().getTime() - offset)) + "," + Math.toDegrees(cut.getBearingRads()) + newLine); } } } // hmm, did we find anything if (res.length() > 0) { // ok, put it on the clipboard. new TextTransfer().setClipboardContents(res.toString()); } } } static final class TextTransfer implements ClipboardOwner { private TextTransfer() { } @Override public void lostOwnership(Clipboard aClipboard, Transferable aContents) { // do nothing } /** * Place a String on the clipboard, and make this class the owner of the * Clipboard's contents. */ public void setClipboardContents(String aString) { StringSelection stringSelection = new StringSelection(aString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); } } }
package test.com.wirelust.personalapi.api.v1.resources; import javax.enterprise.inject.Produces; import javax.inject.Inject; import com.wirelust.personalapi.api.exceptions.ApiException; import com.wirelust.personalapi.api.v1.representations.EnumErrorCode; import com.wirelust.personalapi.api.v1.resources.AccountResource; import com.wirelust.personalapi.data.model.Account; import com.wirelust.personalapi.data.model.ApiApplication; import com.wirelust.personalapi.data.repositories.AccountRepository; import com.wirelust.personalapi.data.repositories.ApiApplicationRepository; import com.wirelust.personalapi.data.repositories.AuthorizationRepository; import com.wirelust.personalapi.data.repositories.RestrictedUsernameRepository; import com.wirelust.personalapi.services.AccountService; import com.wirelust.personalapi.services.Configuration; import org.jglue.cdiunit.CdiRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; @RunWith(CdiRunner.class) public class AccountResourceTest { @Inject AccountResource accountResource; @Produces @Mock ApiApplicationRepository apiApplicationRepository; @Produces @Mock AccountService accountService; @Produces @Mock AuthorizationRepository authorizationRepository; @Produces @Mock AccountRepository accountRepository; @Produces @Mock Configuration configuration; @Produces @Mock RestrictedUsernameRepository restrictedUsernameRepository; @Test public void shouldThrowExceptionWhenRegisterGetsInvalidClientId() { try { accountResource.register("clientId", null, null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.CLIENT_ID_INVALID, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsInvalidUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(false); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_INVALID, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsExistingUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(true); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsRestrictedUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(false); when(restrictedUsernameRepository.isRestricted(any(String.class))).thenReturn(true); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsDuplicateEmail() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(false); when(restrictedUsernameRepository.isRestricted(any(String.class))).thenReturn(false); when(accountRepository.findAnyByEmail(any(String.class))).thenReturn(new Account()); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.EMAIL_EXISTS, e.getErrorCode()); } } @Test public void shouldBeAbleToCheckForUsername() { when(accountRepository.usernameExists(any(String.class))).thenReturn(true); try { accountResource.checkUsername("username"); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } @Test public void shouldBeAbleToCheckForRestrictedUsername() { when(accountRepository.usernameExists(any(String.class))).thenReturn(false); when(restrictedUsernameRepository.isRestricted(any(String.class))).thenReturn(true); try { accountResource.checkUsername("username"); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } }
package carpentersblocks.util; import net.minecraft.block.Block; import net.minecraft.block.BlockBreakable; import net.minecraft.block.BlockHalfSlab; import net.minecraft.block.BlockPane; import net.minecraft.block.BlockQuartz; import net.minecraft.block.StepSound; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import carpentersblocks.tileentity.TEBase; import carpentersblocks.util.handler.OverlayHandler; public class BlockProperties { public final static StepSound stepSound = new StepSound("carpentersblock", 1.0F, 1.0F); /** * Returns depth of side cover. */ public static float getSideCoverDepth(TEBase TE, int side) { if (getOverlay(TE, side) == OverlayHandler.OVERLAY_SNOW) { return 0.125F; } else { return 0.0625F; } } /** * Returns entity facing. */ public static int getEntityFacing(Entity entity) { return MathHelper.floor_double(entity.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; } /** * Returns RGB of dye metadata. */ public static float[] getDyeRGB(int metadata) { int color = ItemDye.dyeColors[15 - metadata]; float red = (color >> 16 & 255) / 255.0F; float green = (color >> 8 & 255) / 255.0F; float blue = (color & 255) / 255.0F; float[] rgb = { red, green, blue }; return rgb; } /** * Similar to ForgeDirection.OPPOSITES[], except for entity facing. */ public static int getOppositeFacing(int facing) { switch (facing) { case 0: return 2; case 1: return 3; case 2: return 0; default: return 1; } } /** * Will return direction from entity facing. */ public static ForgeDirection getDirectionFromFacing(int facing) { switch (facing) { case 0: return ForgeDirection.NORTH; case 1: return ForgeDirection.EAST; case 2: return ForgeDirection.SOUTH; default: return ForgeDirection.WEST; } } /** * Will suppress block updates. */ private static boolean suppressUpdate = false; /** * Ejects an item at given coordinates. */ public static void ejectEntity(TEBase TE, ItemStack itemStack) { if (!TE.worldObj.isRemote) { float offset = 0.7F; double xRand = TE.worldObj.rand.nextFloat() * offset + (1.0F - offset) * 0.5D; double yRand = TE.worldObj.rand.nextFloat() * offset + (1.0F - offset) * 0.2D + 0.6D; double zRand = TE.worldObj.rand.nextFloat() * offset + (1.0F - offset) * 0.5D; EntityItem entityEjectedItem = new EntityItem(TE.worldObj, TE.xCoord + xRand, TE.yCoord + yRand, TE.zCoord + zRand, itemStack); entityEjectedItem.delayBeforeCanPickup = 10; TE.worldObj.spawnEntityInWorld(entityEjectedItem); } } /** * Returns whether block has an owner. * This is mainly for older blocks before ownership was implemented. */ public static boolean hasOwner(TEBase TE) { return !TE.getOwner().equals(""); } /** * Returns owner of block. */ public static String getOwner(TEBase TE) { return TE.getOwner(); } /** * Sets owner of block. */ public static void setOwner(TEBase TE, EntityLivingBase entityPlayer) { TE.setOwner(entityPlayer.getEntityName()); TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } /** * Returns whether block rotates based on placement conditions. * The blocks that utilize this property are mostly atypical, and * must be added manually. */ public static boolean blockRotates(World world, Block block, int x, int y, int z) { return block.isWood(world, x, y, z) || block instanceof BlockQuartz; } /** * Plays block sound. */ public static void playBlockSound(TEBase TE, Block block) { playBlockSound(TE.worldObj, block, TE.xCoord, TE.yCoord, TE.zCoord); } /** * Plays block sound. */ public static void playBlockSound(World world, Block block, int x, int y, int z) { world.playSoundEffect(x + 0.5F, y + 0.5F, z + 0.5F, block.stepSound.getPlaceSound(), block.stepSound.getVolume() + 1.0F / 2.0F, block.stepSound.getPitch() * 0.8F); } /** * Returns whether block or side block has an attribute. * It checks for cover, dye color and overlay. */ public static boolean hasAttribute(TEBase TE, int side) { return hasCover(TE, side) || hasDyeColor(TE, side) || hasOverlay(TE, side); } /** * Strips side of all properties. */ public static void clearAttributes(TEBase TE, int side) { suppressUpdate = true; setDyeColor(TE, side, 0); setOverlay(TE, side, (ItemStack)null); setCover(TE, side, 0, (ItemStack)null); setPattern(TE, side, 0); suppressUpdate = false; TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } /** * Returns cover block ID. */ public static int getCoverID(TEBase TE, int side) { return TE.cover[side] & 0xfff; } /** * Returns cover block metadata. */ public static int getCoverMetadata(TEBase TE, int side) { return (TE.cover[side] & 0xf000) >>> 12; } /** * Returns whether block has a cover. * Checks if block ID exists and whether it is a valid cover block. */ public static boolean hasCover(TEBase TE, int side) { int coverID = getCoverID(TE, side); int metadata = getCoverMetadata(TE, side); return coverID > 0 && Block.blocksList[coverID] != null && isCover(new ItemStack(coverID, 1, metadata)); } /** * Returns whether block has side covers. */ public static boolean hasSideCovers(TEBase TE) { for (int side = 0; side < 6; ++side) { if (hasCover(TE, side)) { return true; } } return false; } /** * Returns cover block. */ public static Block getCoverBlock(IBlockAccess world, int side, int x, int y, int z) { TEBase TE = (TEBase) world.getBlockTileEntity(x, y, z); return getCoverBlock(TE, side); } /** * Returns cover block. */ public static Block getCoverBlock(TEBase TE, int side) { Block coverBlock; if (hasCover(TE, side)) { coverBlock = Block.blocksList[getCoverID(TE, side)]; } else { coverBlock = Block.blocksList[TE.worldObj.getBlockId(TE.xCoord, TE.yCoord, TE.zCoord)]; } return coverBlock; } /** * Returns whether block is a cover. */ public static boolean isCover(ItemStack itemStack) { if (itemStack.getItem() instanceof ItemBlock && !isOverlay(itemStack)) { Block block = Block.blocksList[itemStack.getItem().itemID]; return !block.hasTileEntity(itemStack.getItemDamage()) && ( block.renderAsNormalBlock() || block instanceof BlockHalfSlab || block instanceof BlockPane || block instanceof BlockBreakable ); } return false; } /** * Converts ItemStack block metadata to correct value. * Things like logs should always drop with metadata 0, even if * a rotation in metadata is set. */ public static ItemStack getFilteredBlock(ItemStack itemStack) { if (itemStack != null) { int damageDropped = Block.blocksList[itemStack.itemID].damageDropped(itemStack.getItemDamage()); if (damageDropped != itemStack.getItemDamage()) { itemStack.setItemDamage(damageDropped); } } return itemStack; } /** * Sets cover block. */ public static boolean setCover(TEBase TE, int side, int metadata, ItemStack itemStack) { if (hasCover(TE, side)) { ejectEntity(TE, getFilteredBlock(new ItemStack(getCoverID(TE, side), 1, getCoverMetadata(TE, side)))); } int blockID = itemStack == null ? 0 : itemStack.itemID; TE.cover[side] = (short) (blockID + (metadata << 12)); if (side == 6) { TE.worldObj.setBlockMetadataWithNotify(TE.xCoord, TE.yCoord, TE.zCoord, metadata, 0); } TE.worldObj.notifyBlocksOfNeighborChange(TE.xCoord, TE.yCoord, TE.zCoord, blockID); TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); return true; } /** * Get block data. * Will handle signed data types automatically. */ public final static int getData(TEBase TE) { return TE.data & 0xffff; } /** * Set block data. */ public static void setData(TEBase TE, int data) { /* No need to update if data hasn't changed. */ if (data != getData(TE)) { TE.data = (short) data; if (!suppressUpdate) { TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } } } /** * Returns whether side has cover. */ public static boolean hasDyeColor(TEBase TE, int side) { return TE.color[side] > 0; } /** * Sets color for side. */ public static boolean setDyeColor(TEBase TE, int side, int metadata) { if (TE.color[side] > 0) { ejectEntity(TE, new ItemStack(Item.dyePowder, 1, 15 - TE.color[side])); } TE.color[side] = (byte) metadata; if (!suppressUpdate) { TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } return true; } /** * Returns dye color for side. */ public static int getDyeColor(TEBase TE, int side) { return TE.color[side]; } /** * Sets overlay. */ public static boolean setOverlay(TEBase TE, int side, ItemStack itemStack) { if (hasOverlay(TE, side)) { ejectEntity(TE, OverlayHandler.getItemStack(TE.overlay[side])); } TE.overlay[side] = (byte) OverlayHandler.getKey(itemStack); if (!suppressUpdate) { TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } return true; } /** * Returns overlay. */ public static int getOverlay(TEBase TE, int side) { return TE.overlay[side]; } /** * Returns whether block has overlay. */ public static boolean hasOverlay(TEBase TE, int side) { return TE.overlay[side] > 0; } /** * Returns whether ItemStack contains a valid overlay item or block. */ public static boolean isOverlay(ItemStack itemStack) { return OverlayHandler.overlayMap.containsValue(itemStack.itemID); } /** * Returns whether block has pattern. */ public static boolean hasPattern(TEBase TE, int side) { return getPattern(TE, side) > 0; } /** * Returns pattern. */ public static int getPattern(TEBase TE, int side) { return TE.pattern[side] & 0xffff; } /** * Sets pattern. */ public static boolean setPattern(TEBase TE, int side, int pattern) { TE.pattern[side] = (byte) pattern; if (!suppressUpdate) { TE.worldObj.markBlockForUpdate(TE.xCoord, TE.yCoord, TE.zCoord); } return true; } /** * Returns whether side should render based on cover blocks * of both source and adjacent block. */ public static boolean shouldRenderSharedFaceBasedOnCovers(TEBase TE_adj, TEBase TE_src) { Block block_adj= BlockProperties.getCoverBlock(TE_adj, 6); Block block_src = BlockProperties.getCoverBlock(TE_src, 6); if (!BlockProperties.hasCover(TE_adj, 6)) { return BlockProperties.hasCover(TE_src, 6); } else { if (!BlockProperties.hasCover(TE_src, 6) && block_adj.getRenderBlockPass() == 0) { return !block_adj.isOpaqueCube(); } else if (BlockProperties.hasCover(TE_src, 6) && block_src.isOpaqueCube() == block_adj.isOpaqueCube() && block_src.getRenderBlockPass() == block_adj.getRenderBlockPass()) { return false; } else { return true; } } } }
import java.awt.Color; public class SeamCarver { private static final double BORDERENERGY = 195075.0; private static final double EPS = 1e-12; private Picture picture; private double[][] distance; public SeamCarver(Picture picture) { this.picture = picture; } public Picture picture() { return this.picture; } public int width() { return picture.width(); } public int height() { return picture.height(); } private double pow2(int value) { return 1.0 * value * value; } private double min(double x, double y) { if (x > y) { return y; } else { return x; } } private double min(double x, double y, double z) { return min(z, min(x, y)); } private boolean equal(double x, double y) { return Math.abs(x - y) < EPS; } public double energy(int x, int y) { if (x < 0 || x > width() - 1 || y < 0 || y > height() - 1) { throw new IndexOutOfBoundsException(); } if (x == 0 || x == width() - 1 || y == 0 || y == height() - 1) { return BORDERENERGY; } Color x1 = picture.get(x - 1, y), x2 = picture.get(x + 1, y), y1 = picture.get(x, y - 1), y2 = picture.get(x, y + 1); return pow2(x1.getRed() - x2.getRed()) + pow2(x1.getGreen() - x2.getGreen()) + pow2(x1.getBlue() - x2.getBlue()) + pow2(y1.getRed() - y2.getRed()) + pow2(y1.getGreen() - y2.getGreen()) + pow2(y1.getBlue() - y2.getBlue()); } public int[] findHorizontalSeam() { int[] result = new int[width()]; distance = new double[height()][width()]; for (int i = 0; i < height(); i++) { distance[i][0] = 0.0; } for (int i = 1; i < width() - 1; ++i) { for (int j = 1; j < height() - 1; ++j) { if (j == 1 && j == height() - 2) { distance[j][i] = distance[j][i - 1] + energy(i, j); } else if (j == 1) { distance[j][i] = min(distance[j][i - 1], distance[j + 1][i - 1]) + energy(i, j); } else if (j == height() - 2) { distance[j][i] = min(distance[j - 1][i - 1], distance[j][i - 1]) + energy(i, j); } else { distance[j][i] = min(distance[j - 1][i - 1], distance[j][i - 1], distance[j + 1][i - 1]) + energy(i, j); } } } double minimalDistance = Double.MAX_VALUE; int index = 0; for (int i = 1; i < height() - 1; ++i) { distance[i][width() - 1] = distance[i][width() - 2] + BORDERENERGY; if (distance[i][width() - 1] < minimalDistance) { minimalDistance = distance[i][width() - 1]; index = i; } } for (int i = width() - 1; i >= 1; --i) { for (int j = 1; j <= height() - 2; ++j) { if (equal(minimalDistance, distance[j - 1][i]) && Math.abs(index - j + 1) <= 1) { result[i] = j - 1; minimalDistance -= energy(i, j - 1); index = j - 1; break; } else if (equal(minimalDistance, distance[j][i]) && Math.abs(index - j) <= 1) { result[i] = j; minimalDistance -= energy(i, j); index = j; break; } else if (equal(minimalDistance, distance[j + 1][i]) && Math.abs(index - j - 1) <= 1) { result[i] = j + 1; minimalDistance -= energy(i, j + 1); index = j + 1; break; } } } result[width() - 1] = result[width() - 2] - 1; result[0] = result[1] - 1; return result; } public int[] findVerticalSeam() { int[] result = new int[height()]; distance = new double[height()][width()]; for (int i = 0; i < width(); ++i) { distance[0][i] = 0.0; } for (int i = 1; i < height() - 1; ++i) { for (int j = 1; j < width() - 1; ++j) { if (j == 1 && j == width() - 2) { distance[i][j] = distance[i - 1][j] + energy(j, i); } else if (j == 1) { distance[i][j] = min(distance[i - 1][j], distance[i - 1][j + 1]) + energy(j, i); } else if (j == width() - 2) { distance[i][j] = min(distance[i - 1][j - 1], distance[i - 1][j]) + energy(j, i); } else { distance[i][j] = min(distance[i - 1][j - 1], distance[i - 1][j], distance[i - 1][j + 1]) + energy(j, i); } } } double minimalDistance = Double.MAX_VALUE; int index = 0; for (int i = 1; i < width() - 1; ++i) { distance[height() - 1][i] = distance[height() - 2][i] + BORDERENERGY; if (distance[height() - 1][i] < minimalDistance) { index = i; minimalDistance = distance[height() - 1][i]; } } for (int i = height() - 1; i >= 1; --i) { for (int j = 1; j <= width() - 2; ++j) { if (equal(minimalDistance, distance[i][j - 1]) && Math.abs(index - j + 1) <= 1) { result[i] = j - 1; minimalDistance -= energy(j - 1, i); index = j - 1; break; } else if (equal(minimalDistance, distance[i][j]) && Math.abs(index - j) <= 1) { result[i] = j; minimalDistance -= energy(j, i); index = j; break; } else if (equal(minimalDistance, distance[i][j + 1]) && Math.abs(index - j - 1) <= 1) { result[i] = j + 1; minimalDistance -= energy(j + 1, i); index = j + 1; break; } } } result[height() - 1] = result[height() - 2] - 1; result[0] = result[1] - 1; return result; } public void removeHorizontalSeam(int[] seam) { if (height() <= 1 || seam.length != width()) { throw new IllegalArgumentException(); } Picture modified = new Picture(width(), height() - 1); int old = seam[0]; for (int i = 0; i < seam.length; ++i) { if (Math.abs(seam[i] - old) > 1) { throw new IllegalArgumentException(); } for (int j = 0; j < seam[i]; ++j) { modified.set(i, j, picture.get(i, j)); } for (int j = seam[i]; j < height() - 1; ++j) { modified.set(i, j, picture.get(i, j + 1)); } old = seam[i]; } picture = modified; } public void removeVerticalSeam(int[] seam) { if (width() <= 1 || seam.length != height()) { throw new IllegalArgumentException(); } Picture modified = new Picture(width() - 1, height()); int old = seam[0]; for (int i = 0; i < seam.length; ++i) { if (Math.abs(seam[i] - old) > 1) { throw new IllegalArgumentException(); } for (int j = 0; j < seam[i]; ++j) { modified.set(j, i, picture.get(j, i)); } for (int j = seam[i]; j < width() - 1; ++j) { modified.set(j, i, picture.get(j + 1, i)); } old = seam[i]; } picture = modified; } public static void main(String[] args) { Picture picture = new Picture("3x7.png"); SeamCarver carver = new SeamCarver(picture); for (int x = 0; x < carver.height(); ++x) { for (int y = 0; y < carver.width(); ++y) { System.out.print(carver.distance[x][y] + " "); } System.out.println(); } } }
package test.com.wirelust.personalapi.api.v1.resources; import javax.enterprise.inject.Produces; import javax.inject.Inject; import com.wirelust.personalapi.api.exceptions.ApiException; import com.wirelust.personalapi.api.v1.representations.EnumErrorCode; import com.wirelust.personalapi.api.v1.resources.AccountResource; import com.wirelust.personalapi.data.model.Account; import com.wirelust.personalapi.data.model.ApiApplication; import com.wirelust.personalapi.data.repositories.AccountRepository; import com.wirelust.personalapi.data.repositories.ApiApplicationRepository; import com.wirelust.personalapi.data.repositories.AuthorizationRepository; import com.wirelust.personalapi.data.repositories.RestrictedUsernameRepository; import com.wirelust.personalapi.services.AccountService; import com.wirelust.personalapi.services.Configuration; import org.jglue.cdiunit.CdiRunner; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; @RunWith(CdiRunner.class) public class AccountResourceTest { @Inject AccountResource accountResource; @Produces @Mock ApiApplicationRepository apiApplicationRepository; @Produces @Mock AccountService accountService; @Produces @Mock AuthorizationRepository authorizationRepository; @Produces @Mock AccountRepository accountRepository; @Produces @Mock Configuration configuration; @Produces @Mock RestrictedUsernameRepository restrictedUsernameRepository; @Test public void shouldThrowExceptionWhenRegisterGetsInvalidClientId() { try { accountResource.register("clientId", null, null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.CLIENT_ID_INVALID, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsInvalidUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(false); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_INVALID, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsExistingUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(true); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsRestrictedUsername() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(false); when(restrictedUsernameRepository.isRestricted(any(String.class))).thenReturn(true); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.USERNAME_EXISTS, e.getErrorCode()); } } @Test public void shouldThrowExceptionWhenRegisterGetsDuplicateEmail() { when(apiApplicationRepository.findBy(any(String.class))).thenReturn(new ApiApplication()); when(accountRepository.usernameIsValid(any(String.class))).thenReturn(true); when(accountRepository.usernameExists(any(String.class))).thenReturn(false); when(restrictedUsernameRepository.isRestricted(any(String.class))).thenReturn(false); when(accountRepository.findAnyByEmail(any(String.class))).thenReturn(new Account()); try { accountResource.register("clientId", "username", null, null, null, null); Assert.fail(); } catch (ApiException e) { assertEquals(EnumErrorCode.EMAIL_EXISTS, e.getErrorCode()); } } }
package be.ephec.nsjc.jws.internal; import java.io.BufferedReader; import java.io.IOException; import be.ephec.nsjc.jws.model.Header; import be.ephec.nsjc.jws.model.Request; public class RequestHandler { BufferedReader reader; /** * Given a http request text to read, prepare the request to be parsed * @param reader the request that will be parsed */ public RequestHandler(BufferedReader reader){ this.reader = reader; } /** * Parse a request text and fill a Request object * @return a Request object * @throws IOException read fail */ public Request parseRequest() throws IOException{ String requestLine = this.reader.readLine(); if(requestLine == null){ //BAD! return null; }else{ String[] reqSplit = requestLine.split(" "); if(reqSplit.length != 3){ //BAD! return null; } Request r = new Request(reqSplit[0], reqSplit[1], reqSplit[2]); r = parseHeaders(r); if(r == null){ //BAD! return r; } r = parseBody(r); return r; } } /** * Parse the body of the request text to fill object * @param r a request object * @return the same request object * @throws IOException read fail */ private Request parseBody(Request r) throws IOException { // TODO if(!r.getMethod().equals("POST")){ //WE CAN SAFELY IGNORE BODY return r; }else{ String body = ""; String line = this.reader.readLine(); while(line != null && line.length() != 0){ body += line+"\r\n"; line = this.reader.readLine(); } body = body.substring(0, body.length()-2); r.setBody(body); } return r; } /** * Parse the headers of the request to fill the object * @param r a request object * @return the same request object * @throws IOException read fail */ private Request parseHeaders(Request r) throws IOException { String line = this.reader.readLine(); Header last = null; while(line != null && line.length() != 0){ if(line.startsWith("\t")){ if(last == null){ //BAD! return null; }else{ last.setLabel(last.getLabel()+"\n"+line); } }else{ if(last != null){ r.addHeader(last); } String[] rawHeader = line.split(": "); last = new Header(rawHeader[0], rawHeader[1]); } line = this.reader.readLine(); } if(last != null){ r.addHeader(last); } return r; } }
package com.intellij.execution.testframework.sm.runner; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.testframework.CompositePrintable; import com.intellij.execution.testframework.Printable; import com.intellij.execution.testframework.Printer; import com.intellij.execution.testframework.TestConsoleProperties; import com.intellij.execution.testframework.sm.runner.events.*; import com.intellij.execution.testframework.sm.runner.ui.MockPrinter; import com.intellij.execution.testframework.sm.runner.ui.SMTRunnerConsoleView; import com.intellij.execution.testframework.sm.runner.ui.SMTestRunnerResultsForm; import com.intellij.execution.testframework.ui.TestsOutputConsolePrinter; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.util.Disposer; import com.intellij.util.concurrency.Semaphore; import org.jetbrains.annotations.NotNull; /** * @author Roman Chernyatchik */ public class SMTRunnerConsoleTest extends BaseSMTRunnerTestCase { private MyConsoleView myConsole; private GeneralToSMTRunnerEventsConvertor myEventsProcessor; private MockPrinter myMockResettablePrinter; private SMTestProxy.SMRootTestProxy myRootSuite; private SMTestRunnerResultsForm myResultsViewer; private class MyConsoleView extends SMTRunnerConsoleView { private final TestsOutputConsolePrinter myTestsOutputConsolePrinter; private MyConsoleView(final TestConsoleProperties consoleProperties) { super(consoleProperties); myTestsOutputConsolePrinter = new TestsOutputConsolePrinter(this, consoleProperties, null) { @Override public void print(final String text, final ConsoleViewContentType contentType) { myMockResettablePrinter.print(text, contentType); } }; } @Override public TestsOutputConsolePrinter getPrinter() { return myTestsOutputConsolePrinter; } } @Override protected void setUp() throws Exception { super.setUp(); final TestConsoleProperties consoleProperties = createConsoleProperties(); myMockResettablePrinter = new MockPrinter(true); myConsole = new MyConsoleView(consoleProperties); myConsole.initUI(); myResultsViewer = myConsole.getResultsViewer(); myRootSuite = myResultsViewer.getTestsRootNode(); myEventsProcessor = new GeneralToSMTRunnerEventsConvertor(consoleProperties.getProject(), myResultsViewer.getTestsRootNode(), "SMTestFramework"); myEventsProcessor.onStartTesting(); } @Override protected void tearDown() throws Exception { try { Disposer.dispose(myEventsProcessor); Disposer.dispose(myConsole); } catch (Throwable e) { addSuppressedException(e); } finally { super.tearDown(); } } public void testPrintTestProxy() { mySimpleTest.setPrinter(myMockResettablePrinter); mySimpleTest.addLast(new Printable() { @Override public void printOn(final Printer printer) { printer.print("std out", ConsoleViewContentType.NORMAL_OUTPUT); printer.print("std err", ConsoleViewContentType.ERROR_OUTPUT); printer.print("std sys", ConsoleViewContentType.SYSTEM_OUTPUT); } }); assertAllOutputs(myMockResettablePrinter, "std out", "std err", "std sys"); } public void testAddStdOut() { mySimpleTest.setPrinter(myMockResettablePrinter); mySimpleTest.addStdOutput("one"); assertStdOutput(myMockResettablePrinter, "one"); mySimpleTest.addStdErr("two"); assertStdErr(myMockResettablePrinter, "two"); mySimpleTest.addStdOutput("one"); mySimpleTest.addStdOutput("one"); mySimpleTest.addStdErr("two"); mySimpleTest.addStdErr("two"); assertAllOutputs(myMockResettablePrinter, "oneone", "twotwo", ""); } public void testAddStdSys() { mySimpleTest.setPrinter(myMockResettablePrinter); mySimpleTest.addSystemOutput("sys"); assertAllOutputs(myMockResettablePrinter, "", "", "sys"); } public void testPrintTestProxy_Order() { mySimpleTest.setPrinter(myMockResettablePrinter); sendToTestProxyStdOut(mySimpleTest, "first "); sendToTestProxyStdOut(mySimpleTest, "second"); assertStdOutput(myMockResettablePrinter, "first second"); } public void testSetPrintListener_ForExistingChildren() { mySuite.addChild(mySimpleTest); mySuite.setPrinter(myMockResettablePrinter); sendToTestProxyStdOut(mySimpleTest, "child "); sendToTestProxyStdOut(mySuite, "root"); assertStdOutput(myMockResettablePrinter, "child root"); } public void testSetPrintListener_OnNewChild() { mySuite.setPrinter(myMockResettablePrinter); sendToTestProxyStdOut(mySuite, "root "); sendToTestProxyStdOut(mySimpleTest, "[child old msg] "); mySuite.addChild(mySimpleTest); sendToTestProxyStdOut(mySuite, "{child added} "); sendToTestProxyStdOut(mySimpleTest, "[child new msg]"); // printer for parent have been already set, thus new // child should immediately print himself on this printer assertStdOutput(myMockResettablePrinter, "root [child old msg] {child added} [child new msg]"); } public void testDeferredPrint() { sendToTestProxyStdOut(mySimpleTest, "one "); sendToTestProxyStdOut(mySimpleTest, "two "); sendToTestProxyStdOut(mySimpleTest, "three"); myMockResettablePrinter.onNewAvailable(mySimpleTest); assertStdOutput(myMockResettablePrinter, "one two three"); myMockResettablePrinter.resetIfNecessary(); assertFalse(myMockResettablePrinter.hasPrinted()); myMockResettablePrinter.onNewAvailable(mySimpleTest); assertStdOutput(myMockResettablePrinter, "one two three"); } public void testProcessor_OnTestStdOutput() { startTestWithPrinter("my_test"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout2", true)); assertStdOutput(myMockResettablePrinter, "stdout1 stdout2"); } public void testProcessor_OnTestStdErr() { startTestWithPrinter("my_test"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr2", false)); assertStdErr(myMockResettablePrinter, "stderr1 stderr2"); } public void testProcessor_OnTestMixedStd() { startTestWithPrinter("my_test"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout2", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr2", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 stdout2", "stderr1 stderr2", ""); } public void testProcessor_OnFailure() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test", "error msg", "method1:1\nmethod2:2", false, null, null)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nerror msg\nmethod1:1\nmethod2:2\nstderr1 ", ""); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); //other output order final SMTestProxy myTest2 = startTestWithPrinter("my_test2"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stderr1 ", false)); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test2", "error msg", "method1:1\nmethod2:2", false, null, null)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); final MockPrinter mockPrinter2 = new MockPrinter(true); mockPrinter2.onNewAvailable(myTest2); assertAllOutputs(mockPrinter2, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); } public void testProcessor_OnFailure_EmptyStacktrace() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test", "error msg", "\n\n", false, null, null)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nerror msg\nstderr1 ", ""); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 \nerror msg\n", ""); } public void testProcessor_OnFailure_Comparision_Strings() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test", "error msg", "method1:1\nmethod2:2", false, "actual", "expected")); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, // std out "stdout1 ", // std err "\n" + "error msg\n" + "expected\n" + "actual\n" + "\n" + "\n" + "method1:1\n" + "method2:2\n" + "stderr1 ", // std sys "Expected :Actual :"); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, // std out "stdout1 ", // std err "stderr1 \nerror msg\n" + "expected\n" + "actual\n" + "\n" + "\n" + "method1:1\nmethod2:2\n", // std sys "Expected :Actual :"); } public void testProcessor_OnFailure_Comparision_MultilineTexts() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test", "error msg", "method1:1\nmethod2:2", false, "this is:\nactual", "this is:\nexpected")); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nerror msg\n" + "\n" + "\n" + "method1:1\n" + "method2:2\n" + "stderr1 ", ""); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 \n" + "error msg\n" + "\n" + "\n" + "method1:1\n" + "method2:2\n", ""); } public void testProcessor_OnError() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test", "error msg", "method1:1\nmethod2:2", true, null, null)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nerror msg\nmethod1:1\nmethod2:2\nstderr1 ", ""); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); //other output order final SMTestProxy myTest2 = startTestWithPrinter("my_test2"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stderr1 ", false)); myEventsProcessor.onTestFailure(new TestFailedEvent("my_test2", "error msg", "method1:1\nmethod2:2", true, null, null)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); final MockPrinter mockPrinter2 = new MockPrinter(true); mockPrinter2.onNewAvailable(myTest2); assertAllOutputs(mockPrinter2, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); } public void testProcessor_OnErrorMsg() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onError("error msg", "method1:1\nmethod2:2", true); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nerror msg\nmethod1:1\nmethod2:2\nstderr1 ", ""); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "\n" + "error msg\n" + "method1:1\n" + "method2:2\n" + "stderr1 ", ""); myEventsProcessor.onTestFinished(new TestFinishedEvent("my_test", 1L)); myTest1.setFinished(); //other output order final SMTestProxy myTest2 = startTestWithPrinter("my_test2"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stderr1 ", false)); myEventsProcessor.onError("error msg", "method1:1\nmethod2:2", true); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); final MockPrinter mockPrinter2 = new MockPrinter(true); mockPrinter2.onNewAvailable(myTest2); assertAllOutputs(mockPrinter2, "stdout1 ", "stderr1 \nerror msg\nmethod1:1\nmethod2:2\n", ""); } public void testProcessor_Suite_OnErrorMsg() { myEventsProcessor.onError("error msg:root", "method1:1\nmethod2:2", true); myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("suite", null)); final SMTestProxy suite = myEventsProcessor.getCurrentSuite(); suite.setPrinter(myMockResettablePrinter); myEventsProcessor.onError("error msg:suite", "method1:1\nmethod2:2", true); assertAllOutputs(myMockResettablePrinter, "", "\n" + "error msg:suite\n" + "method1:1\n" + "method2:2\n", ""); final MockPrinter mockSuitePrinter = new MockPrinter(true); mockSuitePrinter.onNewAvailable(suite); assertAllOutputs(mockSuitePrinter, "", "\n" + "error msg:suite\n" + "method1:1\n" + "method2:2\n", ""); final MockPrinter mockRootSuitePrinter = new MockPrinter(true); mockRootSuitePrinter.onNewAvailable(myRootSuite); assertAllOutputs(mockRootSuitePrinter, "", "\n" + "error msg:root\n" + "method1:1\n" + "method2:2\n" + "\n" + "error msg:suite\n" + "method1:1\n" + "method2:2\n", ""); } public void testProcessor_OnIgnored() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestIgnored(new TestIgnoredEvent("my_test", "ignored msg", null)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 ", "\nignored msg\n"); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 ", "\nignored msg\n"); //other output order final SMTestProxy myTest2 = startTestWithPrinter("my_test2"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stderr1 ", false)); myEventsProcessor.onTestIgnored(new TestIgnoredEvent("my_test2", "ignored msg", null)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 ", "\nignored msg\n"); final MockPrinter mockPrinter2 = new MockPrinter(true); mockPrinter2.onNewAvailable(myTest2); assertAllOutputs(mockPrinter2, "stdout1 ", "stderr1 ", "\nignored msg\n"); } public void testProcessor_OnIgnored_WithStacktrace() { final SMTestProxy myTest1 = startTestWithPrinter("my_test"); myEventsProcessor.onTestIgnored(new TestIgnoredEvent("my_test", "ignored2 msg", "method1:1\nmethod2:2")); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test", "stderr1 ", false)); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "\nmethod1:1\nmethod2:2\nstderr1 ", "\nignored2 msg\n"); final MockPrinter mockPrinter1 = new MockPrinter(true); mockPrinter1.onNewAvailable(myTest1); assertAllOutputs(mockPrinter1, "stdout1 ", "stderr1 \nmethod1:1\nmethod2:2\n", "\nignored2 msg\n"); //other output order final SMTestProxy myTest2 = startTestWithPrinter("my_test2"); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stdout1 ", true)); myEventsProcessor.onTestOutput(new TestOutputEvent("my_test2", "stderr1 ", false)); myEventsProcessor.onTestIgnored(new TestIgnoredEvent("my_test2", "ignored msg", "method1:1\nmethod2:2")); assertAllOutputs(myMockResettablePrinter, "stdout1 ", "stderr1 \nmethod1:1\nmethod2:2\n", "\nignored msg\n"); final MockPrinter mockPrinter2 = new MockPrinter(true); mockPrinter2.onNewAvailable(myTest2); assertAllOutputs(mockPrinter2, "stdout1 ", "stderr1 \nmethod1:1\nmethod2:2\n", "\nignored msg\n"); } public void testOnUncapturedOutput_BeforeProcessStarted() { myRootSuite.setPrinter(myMockResettablePrinter); assertOnUncapturedOutput(); } public void testOnUncapturedOutput_BeforeFirstSuiteStarted() { myRootSuite.setPrinter(myMockResettablePrinter); myEventsProcessor.onStartTesting(); assertOnUncapturedOutput(); } public void testOnUncapturedOutput_SomeSuite() { myEventsProcessor.onStartTesting(); myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("my suite", null)); final SMTestProxy mySuite = myEventsProcessor.getCurrentSuite(); assertNotSame(mySuite, myRootSuite); mySuite.setPrinter(myMockResettablePrinter); assertOnUncapturedOutput(); } public void testOnUncapturedOutput_SomeTest() { myEventsProcessor.onStartTesting(); myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("my suite", null)); startTestWithPrinter("my test"); assertOnUncapturedOutput(); } public void assertOnUncapturedOutput() { myEventsProcessor.onUncapturedOutput("stdout", ProcessOutputTypes.STDOUT); myEventsProcessor.onUncapturedOutput("stderr", ProcessOutputTypes.STDERR); myEventsProcessor.onUncapturedOutput("system", ProcessOutputTypes.SYSTEM); assertAllOutputs(myMockResettablePrinter, "stdout", "stderr", "system"); } public static void assertStdOutput(final MockPrinter printer, final String out) { assertAllOutputs(printer, out, "", ""); } public static void assertStdErr(final MockPrinter printer, final String out) { assertAllOutputs(printer, "", out, ""); } public static void assertAllOutputs(final MockPrinter printer, final String out, final String err, final String sys) { assertTrue(printer.hasPrinted()); assertEquals(out, printer.getStdOut()); assertEquals(err, printer.getStdErr()); assertEquals(sys, printer.getStdSys()); printer.resetIfNecessary(); } public void testStopCollectingOutput() { myResultsViewer.selectAndNotify(myResultsViewer.getTestsRootNode()); myEventsProcessor.onStartTesting(); myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("suite", null)); final SMTestProxy suite = myEventsProcessor.getCurrentSuite(); myEventsProcessor.onSuiteFinished(new TestSuiteFinishedEvent("suite")); myEventsProcessor.onUncapturedOutput("preved", ProcessOutputTypes.STDOUT); myEventsProcessor.onFinishTesting(); //myResultsViewer.selectAndNotify(suite); //the string above doesn't update tree immediately so we should simulate update myConsole.getPrinter().updateOnTestSelected(suite); //Lets reset printer /clear console/ before selection changed to //get after selection event only actual ouptut myMockResettablePrinter.resetIfNecessary(); //myResultsViewer.selectAndNotify(myResultsViewer.getTestsRootNode()); //the string above doesn't update tree immediately so we should simulate update myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); assertAllOutputs(myMockResettablePrinter, "preved", "",""); } public void testPrintingOnlyOwnContentForRoot() { myRootSuite.setShouldPrintOwnContentOnly(true); myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); myEventsProcessor.onStartTesting(); myEventsProcessor.onUncapturedOutput("root output 1\n", ProcessOutputTypes.STDOUT); myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("suite", null)); SMTestProxy suite = myEventsProcessor.getCurrentSuite(); myEventsProcessor.onUncapturedOutput("suite output\n", ProcessOutputTypes.STDOUT); myEventsProcessor.onTestStarted(new TestStartedEvent("my test", null)); myEventsProcessor.onUncapturedOutput("test output\n", ProcessOutputTypes.STDOUT); myEventsProcessor.onTestFinished(new TestFinishedEvent("my test", null)); myEventsProcessor.onSuiteFinished(new TestSuiteFinishedEvent("suite")); myEventsProcessor.onUncapturedOutput("root output 2\n", ProcessOutputTypes.STDOUT); myEventsProcessor.onFinishTesting(); assertAllOutputs(myMockResettablePrinter, "root output 1\n" + "root output 2\n", "", ""); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(suite); assertAllOutputs(myMockResettablePrinter, "suite output\n" + "test output\n", "", ""); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); assertAllOutputs(myMockResettablePrinter, "root output 1\n" + "root output 2\n", "", ""); myRootSuite.setShouldPrintOwnContentOnly(false); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(suite); assertAllOutputs(myMockResettablePrinter, "suite output\n" + "test output\n", "", ""); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); assertAllOutputs(myMockResettablePrinter, "root output 1\n" + "suite output\n" + "test output\n" + "root output 2\n", "", ""); } public void testPrintingManyOutputForRootWithoutChildren() { myRootSuite.setShouldPrintOwnContentOnly(true); myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); myEventsProcessor.onStartTesting(); StringBuilder expectedOutput = new StringBuilder(); for (int i = 0; i < 10000; i++) { String text = "root output " + i + "\n"; myEventsProcessor.onUncapturedOutput(text, ProcessOutputTypes.STDOUT); expectedOutput.append(text); } myEventsProcessor.onSuiteStarted(new TestSuiteStartedEvent("suite", null)); SMTestProxy suite = myEventsProcessor.getCurrentSuite(); myEventsProcessor.onUncapturedOutput("suite output\n", ProcessOutputTypes.STDOUT); myEventsProcessor.onFinishTesting(); assertAllOutputs(myMockResettablePrinter, expectedOutput.toString(), "", ""); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(suite); assertAllOutputs(myMockResettablePrinter, "suite output\n", "", ""); myMockResettablePrinter.resetIfNecessary(); myConsole.getPrinter().updateOnTestSelected(myResultsViewer.getTestsRootNode()); assertAllOutputs(myMockResettablePrinter, expectedOutput.toString(), "", ""); } public void testEnsureOrderedClearFlush() { StringBuffer buf = new StringBuffer(); StringBuilder expected = new StringBuilder(); for(int i = 0; i < 100; i++) { expected.append("1"); expected.append("2"); CompositePrintable.invokeInAlarm(() -> buf.append("1"), false); CompositePrintable.invokeInAlarm(() -> buf.append("2"), false); } Semaphore s = new Semaphore(); s.down(); CompositePrintable.invokeInAlarm(s::up, false); assertTrue(s.waitFor(1000)); assertEquals(expected.toString(), buf.toString()); } @NotNull private SMTestProxy startTestWithPrinter(final String testName) { myEventsProcessor.onTestStarted(new TestStartedEvent(testName, null)); final SMTestProxy proxy = myEventsProcessor.getProxyByFullTestName(myEventsProcessor.getFullTestName(testName)); assertNotNull(proxy); proxy.setPrinter(myMockResettablePrinter); return proxy; } private static void sendToTestProxyStdOut(final SMTestProxy proxy, final String text) { proxy.addLast(new Printable() { @Override public void printOn(final Printer printer) { printer.print(text, ConsoleViewContentType.NORMAL_OUTPUT); } }); } }
package org.elasticsearch.xpack.security.support; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.test.SecurityIntegTestCase; import org.elasticsearch.xpack.security.action.user.PutUserRequest; import org.elasticsearch.xpack.security.action.user.PutUserResponse; import org.hamcrest.Matchers; import org.junit.After; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class IndexLifecycleManagerIntegTests extends SecurityIntegTestCase { public void testConcurrentOperationsTryingToCreateSecurityIndexAndAlias() throws Exception { assertSecurityIndexWriteable(); final int processors = Runtime.getRuntime().availableProcessors(); final int numThreads = scaledRandomIntBetween((processors + 1) / 2, 4 * processors); final int maxNumRequests = 100 / numThreads; // bound to a maximum of 100 requests final int numRequests = scaledRandomIntBetween(4, maxNumRequests); final List<ActionFuture<PutUserResponse>> futures = new CopyOnWriteArrayList<>(); final List<Exception> exceptions = new CopyOnWriteArrayList<>(); final Thread[] threads = new Thread[numThreads]; final CyclicBarrier barrier = new CyclicBarrier(threads.length); final AtomicInteger userNumber = new AtomicInteger(0); for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new AbstractRunnable() { @Override public void onFailure(Exception e) { exceptions.add(e); } @Override protected void doRun() throws Exception { final List<PutUserRequest> requests = new ArrayList<>(numRequests); for (int i = 0; i < numRequests; i++) { requests.add(securityClient() .preparePutUser("user" + userNumber.getAndIncrement(), "password".toCharArray(), randomAlphaOfLengthBetween(1, 16)) .request()); } barrier.await(10L, TimeUnit.SECONDS); for (PutUserRequest request : requests) { PlainActionFuture<PutUserResponse> responsePlainActionFuture = new PlainActionFuture<>(); securityClient().putUser(request, responsePlainActionFuture); futures.add(responsePlainActionFuture); } } }, "create_users_thread" + i); threads[i].start(); } for (Thread thread : threads) { thread.join(); } assertThat(exceptions, Matchers.empty()); assertEquals(futures.size(), numRequests * numThreads); for (ActionFuture<PutUserResponse> future : futures) { assertTrue(future.actionGet().created()); } } @After public void cleanupSecurityIndex() throws Exception { super.deleteSecurityIndex(); } }
package com.redhat.ceylon.eclipse.core.builder; import static com.redhat.ceylon.cmr.ceylon.CeylonUtils.repoManager; import static com.redhat.ceylon.compiler.java.util.Util.getModuleArchiveName; import static com.redhat.ceylon.compiler.java.util.Util.getModulePath; import static com.redhat.ceylon.compiler.java.util.Util.getSourceArchiveName; import static com.redhat.ceylon.eclipse.core.builder.CeylonNature.NATURE_ID; import static com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathUtil.getCeylonClasspathContainers; import static com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile.createResourceVirtualFile; import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID; import static org.eclipse.core.resources.IResource.DEPTH_INFINITE; import static org.eclipse.core.resources.IResource.DEPTH_ZERO; import static org.eclipse.core.runtime.SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.tools.DiagnosticListener; import javax.tools.FileObject; import javax.tools.JavaFileObject; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.redhat.ceylon.cmr.api.Logger; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.loader.mirror.JavacClass; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl; import com.redhat.ceylon.compiler.java.tools.CeyloncTool; import com.redhat.ceylon.compiler.java.tools.JarEntryFileObject; import com.redhat.ceylon.compiler.java.tools.LanguageCompiler; import com.redhat.ceylon.compiler.java.util.RepositoryLister; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.js.JsCompiler; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.ModelLoaderFactory; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.model.LazyPackage; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.parser.CeylonParser; import com.redhat.ceylon.compiler.typechecker.parser.LexError; import com.redhat.ceylon.compiler.typechecker.parser.ParseError; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory; import com.redhat.ceylon.eclipse.code.editor.CeylonTaskUtil; import com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathContainer; import com.redhat.ceylon.eclipse.core.model.IResourceAware; import com.redhat.ceylon.eclipse.core.model.JavaCompilationUnit; import com.redhat.ceylon.eclipse.core.model.SourceFile; import com.redhat.ceylon.eclipse.core.model.loader.JDTClass; import com.redhat.ceylon.eclipse.core.model.loader.JDTModelLoader; import com.redhat.ceylon.eclipse.core.model.loader.JDTModuleManager; import com.redhat.ceylon.eclipse.core.model.loader.SourceClass; import com.redhat.ceylon.eclipse.core.typechecker.CrossProjectPhasedUnit; import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit; import com.redhat.ceylon.eclipse.core.vfs.IFileVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.IFolderVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.util.CarUtils; import com.redhat.ceylon.eclipse.util.EclipseLogger; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import com.sun.tools.javac.file.RelativePath.RelativeFile; import com.sun.tools.javac.file.ZipFileIndexCache; /** * A builder may be activated on a file containing ceylon code every time it has * changed (when "Build automatically" is on), or when the programmer chooses to * "Build" a project. * * TODO This default implementation was generated from a template, it needs to * be completed manually. */ public class CeylonBuilder extends IncrementalProjectBuilder { public static final String CEYLON_CLASSES_FOLDER_NAME = ".exploded"; private static boolean compileWithJDTModelLoader = false; /** * Extension ID of the Ceylon builder, which matches the ID in the * corresponding extension definition in plugin.xml. */ public static final String BUILDER_ID = PLUGIN_ID + ".ceylonBuilder"; /** * A marker ID that identifies problems */ public static final String PROBLEM_MARKER_ID = PLUGIN_ID + ".ceylonProblem"; /** * A marker ID that identifies tasks */ public static final String TASK_MARKER_ID = PLUGIN_ID + ".ceylonTask"; public static final String SOURCE = "Ceylon"; private final class BuildFileManager extends CeyloncFileManager { private final IProject project; final boolean explodeModules; private BuildFileManager(com.sun.tools.javac.util.Context context, boolean register, Charset charset, IProject project) { super(context, register, charset); this.project = project; explodeModules = isExplodeModulesEnabled(project); } @Override protected JavaFileObject getFileForOutput(Location location, final RelativeFile fileName, FileObject sibling) throws IOException { JavaFileObject javaFileObject = super.getFileForOutput(location, fileName, sibling); if (explodeModules && javaFileObject instanceof JarEntryFileObject) { final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); final File classFile = fileName.getFile(ceylonOutputDirectory); classFile.getParentFile().mkdirs(); return new ExplodingJavaFileObject(classFile, fileName, javaFileObject); } return javaFileObject; } @Override protected String getCurrentWorkingDir() { return project.getLocation().toFile().getAbsolutePath(); } } public static enum ModelState { Missing, Parsing, Parsed, TypeChecking, TypeChecked, Compiled }; final static Map<IProject, ModelState> modelStates = new HashMap<IProject, ModelState>(); private final static Map<IProject, TypeChecker> typeCheckers = new HashMap<IProject, TypeChecker>(); private final static Map<IProject, List<IFile>> projectSources = new HashMap<IProject, List<IFile>>(); public static final String CEYLON_CONSOLE= "Ceylon Build"; //private long startTime; public static ModelState getModelState(IProject project) { ModelState modelState = modelStates.get(project); if (modelState == null) { return ModelState.Missing; } return modelState; } public static boolean isModelAvailable(IProject project) { ModelState modelState = getModelState(project); return modelState.ordinal() >= ModelState.TypeChecked.ordinal(); } public static List<PhasedUnit> getUnits(IProject project) { if (! isModelAvailable(project)) { return Collections.emptyList(); } List<PhasedUnit> result = new ArrayList<PhasedUnit>(); TypeChecker tc = typeCheckers.get(project); if (tc!=null) { for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } return result; } public static List<PhasedUnit> getUnits() { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); for (IProject project : typeCheckers.keySet()) { if (isModelAvailable(project)) { TypeChecker tc = typeCheckers.get(project); for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } } return result; } public static List<PhasedUnit> getUnits(String[] projects) { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); if (projects!=null) { for (Map.Entry<IProject, TypeChecker> me: typeCheckers.entrySet()) { for (String pname: projects) { if (me.getKey().getName().equals(pname)) { IProject project = me.getKey(); if (isModelAvailable(project)) { result.addAll(me.getValue().getPhasedUnits().getPhasedUnits()); } } } } } return result; } public String getBuilderID() { return BUILDER_ID; } public static boolean isCeylon(IFile file) { String ext = file.getFileExtension(); return ext!=null && ext.equals("ceylon"); } public static boolean isJava(IFile file) { return JavaCore.isJavaLikeFileName(file.getName()); } public static boolean isCeylonOrJava(IFile file) { return isCeylon(file) || isJava(file); } /** * Decide whether a file needs to be build using this builder. Note that * <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should * never return true for the same file. * * @return true iff an arbitrary file is a ceylon source file. */ protected boolean isSourceFile(IFile file) { IPath path = file.getFullPath(); //getProjectRelativePath(); if (path == null) return false; if (!isCeylonOrJava(file)) { return false; } IProject project = file.getProject(); if (project != null) { for (IPath sourceFolder: getSourceFolders(project)) { if (sourceFolder.isPrefixOf(path)) { return true; } } } return false; } public static JDTModelLoader getModelLoader(TypeChecker tc) { return (JDTModelLoader) ((JDTModuleManager) tc.getPhasedUnits() .getModuleManager()).getModelLoader(); } public static JDTModelLoader getProjectModelLoader(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return getModelLoader(typeChecker); } final static class BooleanHolder { public boolean value; } @Override protected IProject[] build(final int kind, Map args, IProgressMonitor mon) throws CoreException { final IProject project = getProject(); IJavaProject javaProject = JavaCore.create(project); SubMonitor monitor = SubMonitor.convert(mon, "Ceylon build of project " + project.getName(), 100); IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); for (IMarker m: buildMarkers) { Object message = m.getAttribute("message"); if (message!=null && message.toString().endsWith("'JDTClasses'")) { //ignore message from JDT about missing JDTClasses dir m.delete(); } else if (message!=null && message.toString().contains("is missing required Java project:")) { return project.getReferencedProjects(); } } List<CeylonClasspathContainer> cpContainers = getCeylonClasspathContainers(javaProject); if (cpContainers.isEmpty()) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "the Ceylon classpath container is not set on the project " + project.getName() + " (try running Enable Ceylon Builder on the project)"); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } List<PhasedUnit> builtPhasedUnits = Collections.emptyList(); final BooleanHolder mustDoFullBuild = new BooleanHolder(); final BooleanHolder mustResolveClasspathContainer = new BooleanHolder(); final IResourceDelta currentDelta = getDelta(getProject()); List<IResourceDelta> projectDeltas = new ArrayList<IResourceDelta>(); projectDeltas.add(currentDelta); for (IProject requiredProject : project.getReferencedProjects()) { projectDeltas.add(getDelta(requiredProject)); } boolean somethingToDo = chooseBuildTypeFromDeltas(kind, project, projectDeltas, mustDoFullBuild, mustResolveClasspathContainer); if (!somethingToDo && (args==null || !args.containsKey(BUILDER_ID + ".reentrant"))) { return project.getReferencedProjects(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (mustResolveClasspathContainer.value) { if (cpContainers != null) { for (CeylonClasspathContainer container: cpContainers) { boolean changed = container.resolveClasspath(monitor, true); if(changed) { JavaCore.setClasspathContainer(container.getPath(), new IJavaProject[]{javaProject}, new IClasspathContainer[]{null} , monitor); container.refreshClasspathContainer(monitor, javaProject); } } } } try { // startTime = System.nanoTime(); /*IBuildConfiguration[] buildConfsBefore = getContext().getAllReferencedBuildConfigs(); if (buildConfsBefore.length == 0) { //don't clear the console unless //we are the first project in //the build invocation findConsole().clearConsole(); }*/ // getConsoleStream().println(timedMessage("Starting Ceylon build on project: " + project.getName())); boolean binariesGenerationOK; final TypeChecker typeChecker; if (mustDoFullBuild.value) { monitor.subTask("Full Ceylon build of project " + project.getName()); // getConsoleStream().println(timedMessage("Full build of model")); if (monitor.isCanceled()) { throw new OperationCanceledException(); } cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing existing markers of project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } //if (! getModelState(project).equals(ModelState.Parsed)) { if (!mustResolveClasspathContainer.value) { monitor.subTask("Parsing source of project " + project.getName()); //if we already resolved the classpath, the //model has already been freshly-parsed typeChecker = parseCeylonModel(project, monitor.newChild(5, PREPEND_MAIN_LABEL_TO_SUBTASK)); monitor.worked(1); } else { typeChecker = getProjectTypeChecker(project); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Typechecking all source files of project " + project.getName()); modelStates.put(project, ModelState.TypeChecking); builtPhasedUnits = fullTypeCheck(project, typeChecker, monitor.newChild(35, PREPEND_MAIN_LABEL_TO_SUBTASK )); modelStates.put(project, ModelState.TypeChecked); monitor.worked(1); //we do this before the binary generation, in order to //display the errors quicker, but if the backend starts //adding its own errors, we should do it afterwards monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(typeChecker.getPhasedUnits().getPhasedUnits(), project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Generating binaries for project " + project.getName()); final List<IFile> allSources = getProjectSources(project); // getConsoleStream().println(timedMessage("Full generation of class files...")); // getConsoleStream().println(" ...compiling " + // allSources.size() + " source files..."); binariesGenerationOK = generateBinaries(project, javaProject, allSources, typeChecker, monitor.newChild(45, PREPEND_MAIN_LABEL_TO_SUBTASK)); // getConsoleStream().println(successMessage(binariesGenerationOK)); monitor.worked(1); } else { monitor.subTask("Incremental Ceylon build of project " + project.getName()); // getConsoleStream().println(timedMessage("Incremental build of model")); List<IFile> filesToRemove = new ArrayList<IFile>(); Set<IFile> changedSources = new HashSet<IFile>(); monitor.subTask("Scanning deltas of project " + project.getName()); calculateChangedSources(currentDelta, projectDeltas, filesToRemove, changedSources, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } typeChecker = typeCheckers.get(project); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); monitor.subTask("Scanning dependencies of deltas of project " + project.getName()); final Collection<IFile> sourceToCompile= new HashSet<IFile>(); calculateDependencies(project, sourceToCompile, currentDelta, changedSources, typeChecker, phasedUnits, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Cleaning removed files for project " + project.getName()); cleanRemovedSources(filesToRemove, phasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } /*if (emitDiags) { getConsoleStream().println("All files to compile:"); dumpSourceList(sourceToCompile); }*/ monitor.subTask("Compiling " + sourceToCompile.size() + " source files in project " + project.getName()); builtPhasedUnits = incrementalBuild(project, sourceToCompile, monitor.newChild(35, PREPEND_MAIN_LABEL_TO_SUBTASK)); if (builtPhasedUnits.isEmpty() && sourceToCompile.isEmpty()) { return project.getReferencedProjects(); } monitor.worked(1); //we do this before the binary generation, in order to //display the errors quicker, but if the backend starts //adding its own errors, we should do it afterwards monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(builtPhasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Generating binaries for project " + project.getName()); // getConsoleStream().println(timedMessage("Incremental generation of class files...")); // getConsoleStream().println(" ...compiling " + // sourceToCompile.size() + " source files..."); binariesGenerationOK = generateBinaries(project, javaProject, sourceToCompile, typeChecker, monitor.newChild(45, PREPEND_MAIN_LABEL_TO_SUBTASK)); // getConsoleStream().println(successMessage(binariesGenerationOK)); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Updating referencing projects of project " + project.getName()); // getConsoleStream().println(timedMessage("Updating model in referencing projects")); updateExternalPhasedUnitsInReferencingProjects(project, builtPhasedUnits); monitor.worked(1); } if (!binariesGenerationOK) { // Add a problem marker if binary generation went wrong for ceylon files addBinaryGenerationProblemMarker(project); //findConsole().activate(); //TODO: show the Problems view?? } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Collecting dependencies of project " + project.getName()); // getConsoleStream().println(timedMessage("Collecting dependencies")); collectDependencies(project, typeChecker, builtPhasedUnits); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (isExplodeModulesEnabled(project)) { monitor.subTask("Rebuilding using exploded modules directory of " + project.getName()); sheduleIncrementalRebuild(args, project, monitor); monitor.worked(1); } monitor.done(); if (mustDoFullBuild.value) { warmupCompletionProcessor(project, typeChecker); } return project.getReferencedProjects(); } finally { // getConsoleStream().println(timedMessage("End Ceylon build on project: " + project.getName())); } } private void warmupCompletionProcessor(final IProject project, final TypeChecker typeChecker) { Job job = new WarmupJob(project.getName(), typeChecker); job.setPriority(Job.BUILD); //job.setSystem(true); job.setRule(project.getWorkspace().getRoot()); job.schedule(); } private void sheduleIncrementalRebuild(Map args, final IProject project, IProgressMonitor monitor) { try { getCeylonClassesOutputFolder(project).refreshLocal(DEPTH_INFINITE, monitor); } catch (CoreException e) { e.printStackTrace(); }//monitor); if (args==null || !args.containsKey(BUILDER_ID + ".reentrant")) { Job job = new Job("Rebuild with Ceylon classes") { @Override protected IStatus run(IProgressMonitor monitor) { try { //we have already done a build of both the Java and Ceylon classes //so now go back and try to build the both the Java and Ceylon //classes again, using the classes we previously generated - this //is to allow references from Java to Ceylon project.build(INCREMENTAL_BUILD, JavaCore.BUILDER_ID, null, monitor); Map<String,String> map = new HashMap<String,String>(); map.put(BUILDER_ID + ".reentrant", "true"); project.build(INCREMENTAL_BUILD, BUILDER_ID, map, monitor); } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }; job.setRule(project.getWorkspace().getRoot()); job.schedule(); } } private void collectDependencies(IProject project, TypeChecker typeChecker, List<PhasedUnit> builtPhasedUnits) throws CoreException { for (PhasedUnit pu : builtPhasedUnits) { new UnitDependencyVisitor(pu).visit(pu.getCompilationUnit()); } } private void addBinaryGenerationProblemMarker(final IProject project) throws CoreException { /*IMarker marker = project.createMarker(PROBLEM_MARKER_ID); marker.setAttribute(IMarker.MESSAGE, "Bytecode generation has failed on some Ceylon source files in project " + project.getName() + ". Look at the Ceylon console for more information."); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation");*/ } private void cleanRemovedSources(List<IFile> filesToRemove, PhasedUnits phasedUnits, IProject project) { removeObsoleteClassFiles(filesToRemove, project); for (IFile fileToRemove: filesToRemove) { if(isCeylon(fileToRemove)) { // Remove the ceylon phasedUnit (which will also remove the unit from the package) PhasedUnit phasedUnitToDelete = phasedUnits.getPhasedUnit(createResourceVirtualFile(fileToRemove)); if (phasedUnitToDelete != null) { phasedUnits.removePhasedUnitForRelativePath(phasedUnitToDelete.getPathRelativeToSrcDir()); } } else if (isJava(fileToRemove)) { // Remove the external unit from the package Package pkg = retrievePackage(fileToRemove.getParent()); if (pkg != null) { for (Unit unitToTest: pkg.getUnits()) { if (unitToTest.getFilename().equals(fileToRemove.getName())) { pkg.removeUnit(unitToTest); break; } } } } } } private void calculateDependencies(IProject project, Collection<IFile> sourceToCompile, IResourceDelta currentDelta, Set<IFile> fChangedSources, TypeChecker typeChecker, PhasedUnits phasedUnits, IProgressMonitor monitor) { if (!fChangedSources.isEmpty()) { Collection<IFile> changeDependents= new HashSet<IFile>(); changeDependents.addAll(fChangedSources); /*if (emitDiags) { getConsoleStream().println("Changed files:"); dumpSourceList(changeDependents); }*/ boolean changed = false; do { Collection<IFile> additions= new HashSet<IFile>(); for (Iterator<IFile> iter=changeDependents.iterator(); iter.hasNext();) { IFile srcFile= iter.next(); IProject currentFileProject = srcFile.getProject(); TypeChecker currentFileTypeChecker = null; if (currentFileProject == project) { currentFileTypeChecker = typeChecker; } else { currentFileTypeChecker = getProjectTypeChecker(currentFileProject); } Set<String> filesDependingOn = getDependentsOf(srcFile, currentFileTypeChecker, currentFileProject); for (String dependingFile: filesDependingOn) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } //TODO: note that the following is slightly // fragile - it depends on the format // of the path that we use to track // dependents! IPath pathRelativeToProject = new Path(dependingFile); //.makeRelativeTo(project.getLocation()); IFile depFile= (IFile) project.findMember(pathRelativeToProject); if (depFile == null) { depFile= (IFile) currentFileProject.findMember(dependingFile); } if (depFile != null) { additions.add(depFile); } else { System.err.println("could not resolve dependent unit: " + dependingFile); } } } changed = changeDependents.addAll(additions); } while (changed); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnits.getPhasedUnits()) { Unit unit = phasedUnit.getUnit(); if (!unit.getUnresolvedReferences().isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } } Set<Declaration> duplicateDeclarations = unit.getDuplicateDeclarations(); if (!duplicateDeclarations.isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } for (Declaration duplicateDeclaration : duplicateDeclarations) { Unit duplicateUnit = duplicateDeclaration.getUnit(); if ((duplicateUnit instanceof SourceFile) && (duplicateUnit instanceof IResourceAware)) { IFile duplicateDeclFile = ((IResourceAware) duplicateUnit).getFileResource(); if (duplicateDeclFile != null && duplicateDeclFile.exists()) { sourceToCompile.add(duplicateDeclFile); } } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (IFile f: changeDependents) { if (isSourceFile(f) && f.getProject() == project) { if (f.exists()) { sourceToCompile.add(f); } else { // If the file is moved : add a dependency on the new file if (currentDelta != null) { IResourceDelta removedFile = currentDelta.findMember(f.getProjectRelativePath()); if (removedFile != null && (removedFile.getFlags() & IResourceDelta.MOVED_TO) != 0 && removedFile.getMovedToPath() != null) { sourceToCompile.add(project.getFile(removedFile.getMovedToPath().removeFirstSegments(1))); } } } } } } } private void calculateChangedSources(final IResourceDelta currentDelta, List<IResourceDelta> projectDeltas, final List<IFile> filesToRemove, final Set<IFile> changedSources, IProgressMonitor monitor) throws CoreException { for (final IResourceDelta projectDelta: projectDeltas) { if (projectDelta != null) { IProject p = (IProject) projectDelta.getResource(); List<IPath> deltaSourceFolders = getSourceFolders(p); for (IResourceDelta sourceDelta: projectDelta.getAffectedChildren()) { for (IPath ip: deltaSourceFolders) { if (sourceDelta.getResource().getFullPath().isPrefixOf(ip)) { //a real Ceylon source folder so scan for changes /*if (emitDiags) getConsoleStream().println("==> Scanning resource delta for '" + p.getName() + "'... <==");*/ sourceDelta.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource instanceof IFile) { IFile file= (IFile) resource; if (isCeylonOrJava(file)) { changedSources.add(file); if (projectDelta == currentDelta) { if (delta.getKind() == IResourceDelta.REMOVED) { filesToRemove.add((IFile) resource); } } } return false; } return true; } }); /*if (emitDiags) getConsoleStream().println("Delta scan completed for project '" + projectDelta.getResource().getName() + "'...");*/ break; } } } } } } public boolean chooseBuildTypeFromDeltas(final int kind, final IProject project, final List<IResourceDelta> currentDeltas, final BooleanHolder mustDoFullBuild, final BooleanHolder mustResolveClasspathContainer) { mustDoFullBuild.value = kind == FULL_BUILD || kind == CLEAN_BUILD || !isModelAvailable(project); mustResolveClasspathContainer.value = kind==FULL_BUILD; //false; final BooleanHolder sourceModified = new BooleanHolder(); if (!mustDoFullBuild.value) { for (IResourceDelta currentDelta: currentDeltas) { if (currentDelta != null) { try { currentDelta.accept(new DeltaScanner(mustDoFullBuild, project, sourceModified, mustResolveClasspathContainer)); } catch (CoreException e) { e.printStackTrace(); mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } else { mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } } return mustDoFullBuild.value || mustResolveClasspathContainer.value || sourceModified.value; } // private static String successMessage(boolean binariesGenerationOK) { // return " " + (binariesGenerationOK ? // "...binary generation succeeded" : "...binary generation FAILED"); private Set<String> getDependentsOf(IFile srcFile, TypeChecker currentFileTypeChecker, IProject currentFileProject) { if (srcFile.getRawLocation().getFileExtension().equals("ceylon")) { PhasedUnit phasedUnit = currentFileTypeChecker.getPhasedUnits() .getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(srcFile)); if (phasedUnit != null && phasedUnit.getUnit() != null) { return phasedUnit.getUnit().getDependentsOf(); } } else { Unit unit = getJavaUnit(currentFileProject, srcFile); if (unit instanceof JavaCompilationUnit) { return unit.getDependentsOf(); } } return Collections.emptySet(); } private void updateExternalPhasedUnitsInReferencingProjects(IProject project, List<PhasedUnit> builtPhasedUnits) { for (IProject referencingProject : project.getReferencingProjects()) { TypeChecker referencingTypeChecker = getProjectTypeChecker(referencingProject); if (referencingTypeChecker != null) { List<PhasedUnit> referencingPhasedUnits = new ArrayList<PhasedUnit>(); for (PhasedUnit builtPhasedUnit : builtPhasedUnits) { List<PhasedUnits> phasedUnitsOfDependencies = referencingTypeChecker.getPhasedUnitsOfDependencies(); for (PhasedUnits phasedUnitsOfDependency : phasedUnitsOfDependencies) { String relativePath = builtPhasedUnit.getPathRelativeToSrcDir(); PhasedUnit referencingPhasedUnit = phasedUnitsOfDependency.getPhasedUnitFromRelativePath(relativePath); if (referencingPhasedUnit != null) { phasedUnitsOfDependency.removePhasedUnitForRelativePath(relativePath); PhasedUnit newReferencingPhasedUnit = new CrossProjectPhasedUnit(referencingPhasedUnit.getUnitFile(), referencingPhasedUnit.getSrcDir(), builtPhasedUnit.getCompilationUnit(), referencingPhasedUnit.getPackage(), phasedUnitsOfDependency.getModuleManager(), referencingTypeChecker, builtPhasedUnit.getTokens(), project); phasedUnitsOfDependency.addPhasedUnit(newReferencingPhasedUnit.getUnitFile(), newReferencingPhasedUnit); // replace referencingPhasedUnit referencingPhasedUnits.add(newReferencingPhasedUnit); } } } for (PhasedUnit pu : referencingPhasedUnits) { pu.scanDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.scanTypeDeclarations(); } for (PhasedUnit pu : referencingPhasedUnits) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } } } } static PhasedUnit parseFileToPhasedUnit(ModuleManager moduleManager, TypeChecker typeChecker, ResourceVirtualFile file, ResourceVirtualFile srcDir, Package pkg) { ANTLRInputStream input; try { input = new ANTLRInputStream(file.getInputStream(), file.getResource().getProject().getDefaultCharset()); } catch (Exception e) { throw new RuntimeException(e); } CeylonLexer lexer = new CeylonLexer(input); CommonTokenStream tokenStream = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokenStream); Tree.CompilationUnit cu; try { cu = parser.compilationUnit(); } catch (org.antlr.runtime.RecognitionException e) { throw new RuntimeException(e); } List<CommonToken> tokens = new ArrayList<CommonToken>(tokenStream.getTokens().size()); tokens.addAll(tokenStream.getTokens()); List<LexError> lexerErrors = lexer.getErrors(); for (LexError le : lexerErrors) { cu.addLexError(le); } lexerErrors.clear(); List<ParseError> parserErrors = parser.getErrors(); for (ParseError pe : parserErrors) { cu.addParseError(pe); } parserErrors.clear(); PhasedUnit newPhasedUnit = new ProjectPhasedUnit(file, srcDir, cu, pkg, moduleManager, typeChecker, tokens); return newPhasedUnit; } private List<PhasedUnit> incrementalBuild(IProject project, Collection<IFile> sourceToCompile, IProgressMonitor mon) { SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + sourceToCompile.size() + " source files in project " + project.getName(), sourceToCompile.size()*6); TypeChecker typeChecker = typeCheckers.get(project); PhasedUnits pus = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) pus.getModuleManager(); JDTModelLoader modelLoader = getModelLoader(typeChecker); Set<String> cleanedPackages = new HashSet<String>(); List<PhasedUnit> phasedUnitsToUpdate = new ArrayList<PhasedUnit>(); List<Set<String>> dependentsOfList = new ArrayList<Set<String>>(); for (IFile fileToUpdate : sourceToCompile) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } // skip non-ceylon files if(!isCeylon(fileToUpdate)) { if (isJava(fileToUpdate)) { Unit toRemove = getJavaUnit(project, fileToUpdate); if(toRemove != null) { // If the unit is not null, the package should never be null toRemove.getPackage().removeUnit(toRemove); } else { String packageName = getPackageName(fileToUpdate); if (! cleanedPackages.contains(packageName)) { modelLoader.clearCachesOnPackage(packageName); } } continue; } } ResourceVirtualFile file = ResourceVirtualFile.createResourceVirtualFile(fileToUpdate); IPath srcFolderPath = retrieveSourceFolder(fileToUpdate, project); ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); PhasedUnit alreadyBuiltPhasedUnit = pus.getPhasedUnit(file); Package pkg = null; Set<String> dependentsOf = Collections.emptySet(); if (alreadyBuiltPhasedUnit!=null) { // Editing an already built file pkg = alreadyBuiltPhasedUnit.getPackage(); if (alreadyBuiltPhasedUnit.getUnit() != null) { dependentsOf = alreadyBuiltPhasedUnit.getUnit().getDependentsOf(); } } else { IContainer packageFolder = file.getResource().getParent(); pkg = retrievePackage(packageFolder); if (pkg == null) { pkg = createNewPackage(packageFolder); } } PhasedUnit newPhasedUnit = parseFileToPhasedUnit(moduleManager, typeChecker, file, srcDir, pkg); dependentsOfList.add(dependentsOf); phasedUnitsToUpdate.add(newPhasedUnit); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (phasedUnitsToUpdate.size() == 0) { return phasedUnitsToUpdate; } clearProjectMarkers(project); clearMarkersOn(sourceToCompile); for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (pus.getPhasedUnitFromRelativePath(phasedUnit.getPathRelativeToSrcDir()) != null) { pus.removePhasedUnitForRelativePath(phasedUnit.getPathRelativeToSrcDir()); } pus.addPhasedUnit(phasedUnit.getUnitFile(), phasedUnit); } modelLoader.setupSourceFileObjects(phasedUnitsToUpdate); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { phasedUnit.validateTree(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanDeclarations(); } monitor.worked(1); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isTypeDeclarationsScanned()) { monitor.subTask("- scanning type declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanTypeDeclarations(); } monitor.worked(2); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isRefinementValidated()) { phasedUnit.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isFullyTyped()) { monitor.subTask("- typechecking " + phasedUnit.getUnit().getFilename()); phasedUnit.analyseTypes(); if (showWarnings(project)) { phasedUnit.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { phasedUnit.analyseFlow(); } Iterator<Set<String>> itr = dependentsOfList.iterator(); for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { phasedUnit.getUnit().getDependentsOf().addAll(itr.next()); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.done(); return phasedUnitsToUpdate; } private Unit getJavaUnit(IProject project, IFile fileToUpdate) { IJavaElement javaElement = (IJavaElement) fileToUpdate.getAdapter(IJavaElement.class); if (javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IJavaElement packageFragment = compilationUnit.getParent(); JDTModelLoader projectModelLoader = getProjectModelLoader(project); // TODO : Why not use the Model Loader cache to get the declaration // instead of iterating through all the packages ? if (projectModelLoader != null) { Package pkg = projectModelLoader.findPackage(packageFragment.getElementName()); if (pkg != null) { for (Unit unit : pkg.getUnits()) { if (unit.getFilename().equals(fileToUpdate.getName())) { return unit; } } } } } return null; } private List<PhasedUnit> fullTypeCheck(IProject project, TypeChecker typeChecker, IProgressMonitor mon) throws CoreException { List<PhasedUnits> phasedUnitsOfDependencies = typeChecker.getPhasedUnitsOfDependencies(); List<PhasedUnit> dependencies = new ArrayList<PhasedUnit>(); for (PhasedUnits phasedUnits: phasedUnitsOfDependencies) { for (PhasedUnit phasedUnit: phasedUnits.getPhasedUnits()) { dependencies.add(phasedUnit); } } final List<PhasedUnit> listOfUnits = typeChecker.getPhasedUnits().getPhasedUnits(); SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + listOfUnits.size() + " source files of project " + project.getName(), dependencies.size()*5+listOfUnits.size()*6); monitor.subTask("- typechecking source archives for project " + project.getName()); JDTModelLoader loader = getModelLoader(typeChecker); loader.reset(); for (PhasedUnits dependencyPhasedUnits: phasedUnitsOfDependencies) { loader.addSourceArchivePhasedUnits(dependencyPhasedUnits.getPhasedUnits()); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.scanDeclarations(); monitor.worked(1); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning type declarations " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } if (compileWithJDTModelLoader()) { loader.completeFromClasses(); monitor.worked(2); } for (PhasedUnit pu: dependencies) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } Module languageModule = loader.getLanguageModule(); loader.loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", true); loader.loadPackage(languageModule, "ceylon.language", true); loader.loadPackage(languageModule, "ceylon.language.descriptor", true); loader.loadPackageDescriptors(); monitor.subTask("(typechecking source files for project " + project.getName() +")"); for (PhasedUnit pu : listOfUnits) { if (! pu.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.validateTree(); pu.scanDeclarations(); monitor.worked(1); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isTypeDeclarationsScanned()) { monitor.subTask("- scanning types " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { if (! pu.isRefinementValidated()) { pu.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isFullyTyped()) { monitor.subTask("- typechecking " + pu.getUnit().getFilename()); pu.analyseTypes(); if (showWarnings(project)) { pu.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { pu.analyseFlow(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.done(); return typeChecker.getPhasedUnits().getPhasedUnits(); } private boolean compileWithJDTModelLoader() { return compileWithJDTModelLoader; } public static TypeChecker parseCeylonModel(IProject project, IProgressMonitor mon) throws CoreException { modelStates.put(project, ModelState.Parsing); typeCheckers.remove(project); projectSources.remove(project); SubMonitor monitor = SubMonitor.convert(mon, "Setting up typechecker for project " + project.getName(), 5); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final IJavaProject javaProject = JavaCore.create(project); TypeChecker typeChecker = buildTypeChecker(project, javaProject); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) phasedUnits.getModuleManager(); moduleManager.setTypeChecker(typeChecker); Context context = typeChecker.getContext(); JDTModelLoader modelLoader = (JDTModelLoader) moduleManager.getModelLoader(); Module defaultModule = context.getModules().getDefaultModule(); monitor.worked(1); monitor.subTask("- parsing source files for project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } List<IFile> scannedSources = scanSources(project, javaProject, typeChecker, phasedUnits, moduleManager, modelLoader, defaultModule, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } modelLoader.setupSourceFileObjects(typeChecker.getPhasedUnits().getPhasedUnits()); monitor.worked(1); // Parsing of ALL units in the source folder should have been done if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("- determining module dependencies for " + project.getName()); phasedUnits.getModuleManager().prepareForTypeChecking(); phasedUnits.visitModules(); //By now the language module version should be known (as local) //or we should use the default one. Module languageModule = context.getModules().getLanguageModule(); if (languageModule.getVersion() == null) { languageModule.setVersion(TypeChecker.LANGUAGE_MODULE_VERSION); } monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } final ModuleValidator moduleValidator = new ModuleValidator(context, phasedUnits) { @Override protected void executeExternalModulePhases() {} }; moduleValidator.verifyModuleDependencyTree(); typeChecker.setPhasedUnitsOfDependencies(moduleValidator.getPhasedUnitsOfDependencies()); monitor.worked(1); typeCheckers.put(project, typeChecker); projectSources.put(project, scannedSources); modelStates.put(project, ModelState.Parsed); monitor.done(); return typeChecker; } private static TypeChecker buildTypeChecker(IProject project, final IJavaProject javaProject) throws CoreException { TypeCheckerBuilder typeCheckerBuilder = new TypeCheckerBuilder() .verbose(false) .moduleManagerFactory(new ModuleManagerFactory(){ @Override public ModuleManager createModuleManager(Context context) { return new JDTModuleManager(context, javaProject); } }); RepositoryManager repositoryManager = repoManager() .offline(CeylonProjectConfig.get(project).isOffline()) .cwd(project.getLocation().toFile()) .systemRepo(getInterpolatedCeylonSystemRepo(project)) .extraUserRepos(getReferencedProjectsOutputRepositories(project)) .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); typeCheckerBuilder.setRepositoryManager(repositoryManager); TypeChecker typeChecker = typeCheckerBuilder.getTypeChecker(); return typeChecker; } private static List<IFile> scanSources(IProject project, IJavaProject javaProject, final TypeChecker typeChecker, final PhasedUnits phasedUnits, final JDTModuleManager moduleManager, final JDTModelLoader modelLoader, final Module defaultModule, IProgressMonitor monitor) throws CoreException { final List<IFile> scannedSources = new ArrayList<IFile>(); final Collection<IPath> sourceFolders = getSourceFolders(javaProject); for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } srcDirResource.accept(new SourceScanner(defaultModule, modelLoader, moduleManager, srcDir, srcFolderPath, typeChecker, scannedSources, phasedUnits)); } return scannedSources; } private static void addProblemAndTaskMarkers(final List<PhasedUnit> units, final IProject project) { new Job("updating markers for project: " + project) { @Override protected IStatus run(IProgressMonitor monitor) { for (PhasedUnit phasedUnit: units) { IFile file = getFile(phasedUnit); phasedUnit.getCompilationUnit().visit(new MarkerCreator(file)); addTaskMarkers(file, phasedUnit.getTokens()); } return Status.OK_STATUS; } }.schedule(); } private boolean generateBinaries(IProject project, IJavaProject javaProject, Collection<IFile> filesToCompile, TypeChecker typeChecker, IProgressMonitor monitor) throws CoreException { List<String> options = new ArrayList<String>(); List<String> js_srcdir = new ArrayList<String>(); List<String> js_repos = new ArrayList<String>(); boolean js_verbose = false; String js_outRepo = null; String srcPath = ""; for (IPath sourceFolder : getSourceFolders(javaProject)) { File sourcePathElement = toFile(project,sourceFolder .makeRelativeTo(project.getFullPath())); if (! srcPath.isEmpty()) { srcPath += File.pathSeparator; } srcPath += sourcePathElement.getAbsolutePath(); js_srcdir.add(sourcePathElement.getAbsolutePath()); } options.add("-src"); options.add(srcPath); options.add("-encoding"); options.add(project.getDefaultCharset()); for (String repository : getUserRepositories(project)) { options.add("-rep"); options.add(repository); js_repos.add(repository); } String verbose = System.getProperty("ceylon.verbose"); if (verbose!=null && "true".equals(verbose)) { options.add("-verbose"); js_verbose = true; } options.add("-g:lines,vars,source"); String systemRepo = getInterpolatedCeylonSystemRepo(project); if(systemRepo != null && !systemRepo.isEmpty()){ options.add("-sysrep"); options.add(systemRepo); } final File modulesOutputDir = getCeylonModulesOutputDirectory(project); if (modulesOutputDir!=null) { options.add("-out"); options.add(modulesOutputDir.getAbsolutePath()); js_outRepo = modulesOutputDir.getAbsolutePath(); } List<File> javaSourceFiles = new ArrayList<File>(); List<File> sourceFiles = new ArrayList<File>(); List<File> moduleFiles = new ArrayList<File>(); for (IFile file : filesToCompile) { if(isCeylon(file)) { sourceFiles.add(file.getRawLocation().toFile()); if (file.getName().equals(ModuleManager.MODULE_FILE)) { moduleFiles.add(file.getRawLocation().toFile()); } } else if(isJava(file)) javaSourceFiles.add(file.getRawLocation().toFile()); } if (!sourceFiles.isEmpty() || !javaSourceFiles.isEmpty()) { PrintWriter printWriter = new PrintWriter(System.out);//(getConsoleErrorStream(), true); boolean success = true; //Compile JS first if (compileToJs(project) && !sourceFiles.isEmpty()) { Options jsopts = new Options(js_repos, js_srcdir, CeylonBuilder.interpolateVariablesInRepositoryPath(CeylonBuilder.getCeylonSystemRepo(project)), js_outRepo, null/*uname*/, null/*pass*/, true, true, true, true, js_verbose, false, false, false, project.getDefaultCharset(), CeylonProjectConfig.get(project).isOffline()); JsCompiler jsc = new JsCompiler(typeChecker, jsopts).stopOnErrors(false); try { if (!jsc.generate()) { System.out.println("Ceylon-JS compiler failed for " + project.getName()); //TODO report backend errors jsc.printErrors(System.out); return false; } } catch (IOException ex) { ex.printStackTrace(printWriter); } } if (compileToJava(project)) { // always add the java files, otherwise ceylon code won't see them and they won't end up in the archives (src/car) sourceFiles.addAll(javaSourceFiles); if(!sourceFiles.isEmpty()){ success = compile(project, javaProject, options, sourceFiles, typeChecker, printWriter, monitor); } } return success; } else { return true; } } private boolean compile(final IProject project, IJavaProject javaProject, List<String> options, java.util.List<File> sourceFiles, final TypeChecker typeChecker, PrintWriter printWriter, IProgressMonitor mon) throws VerifyError { final SubMonitor monitor = SubMonitor.convert(mon, "Generating binaries for " + sourceFiles.size() + " source files in project " + project.getName(), sourceFiles.size()); CeyloncTool compiler; try { compiler = new CeyloncTool(); } catch (VerifyError e) { System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?"); throw e; } CompileErrorReporter errorReporter = new CompileErrorReporter(project); final com.sun.tools.javac.util.Context context = new com.sun.tools.javac.util.Context(); context.put(com.sun.tools.javac.util.Log.outKey, printWriter); context.put(DiagnosticListener.class, errorReporter); CeylonLog.preRegister(context); BuildFileManager fileManager = new BuildFileManager(context, true, null, project); computeCompilerClasspath(project, javaProject, options); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles); if (compileWithJDTModelLoader()) { setupJDTModelLoader(project, typeChecker, context); } ZipFileIndexCache.getSharedInstance().clearCache(); CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(printWriter, fileManager, errorReporter, options, null, compilationUnits); task.setTaskListener(new TaskListener() { @Override public void started(TaskEvent ta) { String name = ta.getSourceFile().getName(); name = name.substring(name.lastIndexOf("/")+1); monitor.subTask("- compiling " + name); } @Override public void finished(TaskEvent ta) { monitor.worked(1); } }); boolean success=false; try { success = task.call(); } catch (Exception e) { e.printStackTrace(); } if (!success) { errorReporter.failed(); } monitor.done(); return success; } private void computeCompilerClasspath(IProject project, IJavaProject javaProject, List<String> options) { List<String> classpathElements = new ArrayList<String>(); // Modules projectModules = getProjectModules(project); // ArtifactContext ctx; // if (projectModules != null) { // Module languageModule = projectModules.getLanguageModule(); // ctx = new ArtifactContext(languageModule.getNameAsString(), // languageModule.getVersion()); // else { // ctx = new ArtifactContext("ceylon.language", // TypeChecker.LANGUAGE_MODULE_VERSION); // ctx.setSuffix(ArtifactContext.CAR); // RepositoryManager repositoryManager = getProjectRepositoryManager(project); // if (repositoryManager!=null) { // //try { // File languageModuleArchive = repositoryManager.getArtifact(ctx); // classpathElements.add(languageModuleArchive.getAbsolutePath()); // /*} // catch (Exception e) { // e.printStackTrace(); // }*/ IPath workspaceLocation = project.getWorkspace().getRoot().getLocation(); addProjectClasspathElements(classpathElements, workspaceLocation, javaProject); try { for (IProject p: project.getReferencedProjects()) { if(p.isAccessible()){ addProjectClasspathElements(classpathElements, workspaceLocation, JavaCore.create(p)); } } } catch (CoreException ce) { ce.printStackTrace(); } options.add("-classpath"); String classpath = ""; for (String cpElement : classpathElements) { if (! classpath.isEmpty()) { classpath += File.pathSeparator; } classpath += cpElement; } options.add(classpath); } private void setupJDTModelLoader(final IProject project, final TypeChecker typeChecker, final com.sun.tools.javac.util.Context context) { final JDTModelLoader modelLoader = getModelLoader(typeChecker); context.put(LanguageCompiler.ceylonContextKey, typeChecker.getContext()); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(LanguageCompiler.phasedUnitsManagerKey, new JdtPhasedUnitsManager(modelLoader, project, typeChecker)); modelLoader.setSourceFileObjectManager(new JdtSourceFileObjectManager(context, modelLoader)); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(ModelLoaderFactory.class, new ModelLoaderFactory() { @Override public AbstractModelLoader createModelLoader( com.sun.tools.javac.util.Context context) { return modelLoader; } }); } private void addProjectClasspathElements(List<String> classpathElements, IPath workspaceLocation, IJavaProject javaProj) { try { List<CeylonClasspathContainer> containers = getCeylonClasspathContainers(javaProj); for (CeylonClasspathContainer container : containers) { for (IClasspathEntry cpEntry : container.getClasspathEntries()) { if (!isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(cpEntry.getPath().toOSString()); } } } File outputDir = toFile(javaProj.getProject(), javaProj.getOutputLocation() .makeRelativeTo(javaProj.getProject().getFullPath())); classpathElements.add(outputDir.getAbsolutePath()); for (IClasspathEntry cpEntry : javaProj.getResolvedClasspath(true)) { if (isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(workspaceLocation.append(cpEntry.getPath()).toOSString()); } } } catch (JavaModelException e1) { e1.printStackTrace(); } } public static boolean isExplodeModulesEnabled(IProject project) { Map<String,String> args = getBuilderArgs(project); return args.get("explodeModules")!=null || args.get("enableJdtClasses")!=null; } public static boolean showWarnings(IProject project) { return getBuilderArgs(project).get("hideWarnings")==null; } public static boolean compileToJs(IProject project) { return getBuilderArgs(project).get("compileJs")!=null; } public static boolean compileToJava(IProject project) { return getBuilderArgs(project).get("compileJava")==null; } public static String fileName(ClassMirror c) { if (c instanceof JavacClass) { return ((JavacClass) c).classSymbol.classfile.getName(); } else if (c instanceof JDTClass) { return ((JDTClass) c).getFileName(); } else if (c instanceof SourceClass) { return ((SourceClass) c).getModelDeclaration().getUnit().getFilename(); } else { return "another file"; } } public static List<String> getUserRepositories(IProject project) throws CoreException { List<String> userRepos = getCeylonRepositories(project); userRepos.addAll(getReferencedProjectsOutputRepositories(project)); return userRepos; } public static List<String> getAllRepositories(IProject project) throws CoreException { List<String> allRepos = getUserRepositories(project); allRepos.add(CeylonProjectConfig.get(project).getMergedRepositories().getCacheRepository().getUrl()); return allRepos; } public static List<String> getReferencedProjectsOutputRepositories(IProject project) throws CoreException { List<String> repos = new ArrayList<String>(); if (project != null) { for (IProject referencedProject: project.getReferencedProjects()) { if (referencedProject.isOpen() && referencedProject.hasNature(NATURE_ID)) { repos.add(getCeylonModulesOutputDirectory(referencedProject).getAbsolutePath()); } } } return repos; } private static Map<String,String> getBuilderArgs(IProject project) { if (project!=null) { try { for (ICommand c: project.getDescription().getBuildSpec()) { if (c.getBuilderName().equals(BUILDER_ID)) { return c.getArguments(); } } } catch (CoreException e) { e.printStackTrace(); } } return Collections.emptyMap(); } public static List<String> getCeylonRepositories(IProject project) { CeylonProjectConfig projectConfig = CeylonProjectConfig.get(project); List<String> projectLookupRepos = projectConfig.getProjectLocalRepos(); List<String> globalLookupRepos = projectConfig.getGlobalLookupRepos(); List<String> projectRemoteRepos = projectConfig.getProjectRemoteRepos(); List<String> otherRemoteRepos = projectConfig.getOtherRemoteRepos(); List<String> repos = new ArrayList<String>(); repos.addAll(projectLookupRepos); repos.addAll(globalLookupRepos); repos.addAll(projectRemoteRepos); repos.addAll(otherRemoteRepos); return repos; } private static File toFile(IProject project, IPath path) { return project.getFolder(path).getRawLocation().toFile(); } private static void clearMarkersOn(IResource resource) { try { resource.deleteMarkers(TASK_MARKER_ID, false, DEPTH_INFINITE); resource.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_INFINITE); resource.deleteMarkers(PROBLEM_MARKER_ID + ".backend", true, DEPTH_INFINITE); //these are actually errors from the Ceylon compiler, but //we did not bother creating a separate annotation type! resource.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_INFINITE); } catch (CoreException e) { e.printStackTrace(); } } private static void clearProjectMarkers(IProject project) { try { //project.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_ZERO); } catch (CoreException e) { e.printStackTrace(); } } private static void clearMarkersOn(Collection<IFile> files) { for(IFile file: files) { clearMarkersOn(file); } } /*private void dumpSourceList(Collection<IFile> sourcesToCompile) { MessageConsoleStream consoleStream= getConsoleStream(); for(Iterator<IFile> iter= sourcesToCompile.iterator(); iter.hasNext(); ) { IFile srcFile= iter.next(); consoleStream.println(" " + srcFile.getFullPath()); } }*/ // protected static MessageConsoleStream getConsoleStream() { // return findConsole().newMessageStream(); // protected static MessageConsoleStream getConsoleErrorStream() { // final MessageConsoleStream stream = findConsole().newMessageStream(); // //TODO: all this, just to get the color red? can that be right?? // /*try { // getWorkbench().getProgressService().runInUI(getWorkbench().getWorkbenchWindows()[0], // new IRunnableWithProgress() { // // @Override // public void run(IProgressMonitor monitor) throws InvocationTargetException, // InterruptedException { // stream.setColor(getWorkbench().getDisplay().getSystemColor(SWT.COLOR_RED)); // } // }, null); // } // catch (Exception e) { // e.printStackTrace(); // }*/ // return stream; // private String timedMessage(String message) { // long elapsedTimeMs = (System.nanoTime() - startTime) / 1000000; // return String.format("[%1$10d] %2$s", elapsedTimeMs, message); // /** // * Find or create the console with the given name // * @param consoleName // */ // protected static MessageConsole findConsole() { // String consoleName = CEYLON_CONSOLE; // MessageConsole myConsole= null; // final IConsoleManager consoleManager= ConsolePlugin.getDefault().getConsoleManager(); // IConsole[] consoles= consoleManager.getConsoles(); // for(int i= 0; i < consoles.length; i++) { // IConsole console= consoles[i]; // if (console.getName().equals(consoleName)) // myConsole= (MessageConsole) console; // if (myConsole == null) { // myConsole= new MessageConsole(consoleName, // CeylonPlugin.getInstance().getImageRegistry() // .getDescriptor(CeylonResources.BUILDER)); // consoleManager.addConsoles(new IConsole[] { myConsole }); //// consoleManager.showConsoleView(myConsole); // return myConsole; private static void addTaskMarkers(IFile file, List<CommonToken> tokens) { // clearTaskMarkersOn(file); for (CommonToken token : tokens) { if (token.getType() == CeylonLexer.LINE_COMMENT || token.getType() == CeylonLexer.MULTI_COMMENT) { CeylonTaskUtil.addTaskMarkers(token, file); } } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); IProject project = getProject(); // startTime = System.nanoTime(); // getConsoleStream().println(timedMessage("Starting Ceylon clean on project: " + project.getName())); cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing project and source markers for project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project); // getConsoleStream().println(timedMessage("End Ceylon clean on project: " + project.getName())); } private void cleanupJdtClasses(IProgressMonitor monitor, IProject project) { if (isExplodeModulesEnabled(project)) { monitor.subTask("Cleaning exploded modules directory of project " + project.getName()); final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); new RepositoryLister(Arrays.asList(".*")).list(ceylonOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(ceylonOutputDirectory)) { path.delete(); } } }); } } private void cleanupModules(IProgressMonitor monitor, IProject project) { final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); if (modulesOutputDirectory != null) { monitor.subTask("Cleaning existing artifacts of project " + project.getName()); List<String> extensionsToDelete = Arrays.asList(".jar", ".car", ".src", ".sha1"); new RepositoryLister(extensionsToDelete).list(modulesOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(modulesOutputDirectory)) { path.delete(); } } }); } } public static IFile getFile(PhasedUnit phasedUnit) { return ((IFileVirtualFile) phasedUnit.getUnitFile()).getFile(); } // TODO think: doRefresh(file.getParent()); // N.B.: Assumes all // generated files go into parent folder private static List<IFile> getProjectSources(IProject project) { return projectSources.get(project); } public static TypeChecker getProjectTypeChecker(IProject project) { return typeCheckers.get(project); } public static Modules getProjectModules(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getModules(); } public static List<Module> getModulesInProject(IProject project) { List<Module> moduleList = new ArrayList<Module>(); Modules modules = getProjectModules(project); if (modules != null) { IJavaProject javaProject = JavaCore.create(project); for (Module module : modules.getListOfModules()) { if (!module.isDefault() && !module.isJava()) { try { for (IPackageFragment pkg : javaProject.getPackageFragments()) { if (!pkg.isReadOnly() && pkg.getElementName().equals(module.getNameAsString())) { moduleList.add(module); } } } catch (JavaModelException e) { e.printStackTrace(); } } } } return moduleList; } public static RepositoryManager getProjectRepositoryManager(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getRepositoryManager(); } public static Iterable<IProject> getProjects() { return typeCheckers.keySet(); } public static Iterable<TypeChecker> getTypeCheckers() { return typeCheckers.values(); } public static void removeProject(IProject project) { typeCheckers.remove(project); projectSources.remove(project); modelStates.remove(project); CeylonProjectConfig.remove(project); } public static List<IPath> getSourceFolders(IProject project) { //TODO: is the call to JavaCore.create() very expensive?? return getSourceFolders(JavaCore.create(project)); } /** * Read the IJavaProject classpath configuration and populate the ISourceProject's * build path accordingly. */ public static List<IPath> getSourceFolders(IJavaProject javaProject) { if (javaProject.exists()) { try { List<IPath> projectSourceFolders = new ArrayList<IPath>(); for (IClasspathEntry entry: javaProject.getRawClasspath()) { IPath path = entry.getPath(); if (isCeylonSourceEntry(entry)) { projectSourceFolders.add(path); } } return projectSourceFolders; } catch (JavaModelException e) { e.printStackTrace(); } } return Collections.emptyList(); } public static boolean isCeylonSourceEntry(IClasspathEntry entry) { if (entry.getEntryKind()!=IClasspathEntry.CPE_SOURCE) { return false; } /*for (IClasspathAttribute attribute: entry.getExtraAttributes()) { if (attribute.getName().equals("ceylonSource")) { return true; } }*/ for (IPath exclusionPattern : entry.getExclusionPatterns()) { if (exclusionPattern.toString().endsWith(".ceylon")) { return false; } } return true; } private IPath retrieveSourceFolder(IFile file, IProject project) { IPath path = file.getProjectRelativePath(); if (path == null) return null; if (! isCeylonOrJava(file)) return null; return retrieveSourceFolder(path, project); } // path is project-relative private static IPath retrieveSourceFolder(IPath path, IProject project) { if (project != null) { Collection<IPath> sourceFolders = getSourceFolders(project); for (IPath sourceFolderAbsolute : sourceFolders) { IPath sourceFolder = sourceFolderAbsolute.makeRelativeTo(project.getFullPath()); if (sourceFolder.isPrefixOf(path)) { return sourceFolder; } } } return null; } static Package retrievePackage(IResource folder) { IProject project = folder.getProject(); if (project.isOpen()) { String packageName = getPackageName(folder); if (packageName != null) { TypeChecker typeChecker = typeCheckers.get(project); Context context = typeChecker.getContext(); Modules modules = context.getModules(); for (Module module : modules.getListOfModules()) { for (Package p : module.getPackages()) { if (p.getQualifiedNameString().equals(packageName)) { return p; } } } } } return null; } public static String getPackageName(IResource resource) { IProject project = resource.getProject(); IContainer folder = null; if (resource instanceof IFile) { folder = resource.getParent(); } else { folder = (IContainer) resource; } String packageName = null; IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath, project); if (sourceFolder != null) { IPath relativeFolderPath = folderPath.makeRelativeTo(sourceFolder); packageName = relativeFolderPath.toString().replace('/', '.'); } return packageName; } private Package createNewPackage(IContainer folder) { IPath folderPath = folder.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(folderPath, getProject()); if (sourceFolder == null) { return null; } IContainer parent = folder.getParent(); IPath packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); Package parentPackage = null; while (parentPackage == null && ! parent.equals(folder.getProject())) { packageRelativePath = folder.getProjectRelativePath().makeRelativeTo(parent.getProjectRelativePath()); parentPackage = retrievePackage(parent); parent = parent.getParent(); } Context context = typeCheckers.get(folder.getProject()).getContext(); return createPackage(parentPackage, packageRelativePath, context.getModules()); } private Package createPackage(Package parentPackage, IPath packageRelativePath, Modules modules) { String[] packageSegments = packageRelativePath.segments(); if (packageSegments.length == 1) { Package pkg = new LazyPackage(getProjectModelLoader(getProject())); List<String> parentName = null; if (parentPackage == null) { parentName = Collections.emptyList(); } else { parentName = parentPackage.getName(); } final ArrayList<String> name = new ArrayList<String>(parentName.size() + 1); name.addAll(parentName); name.add(packageRelativePath.segment(0)); pkg.setName(name); Module module = null; if (parentPackage != null) { module = parentPackage.getModule(); } if (module == null) { module = modules.getDefaultModule(); } module.getPackages().add(pkg); pkg.setModule(module); return pkg; } else { Package childPackage = createPackage(parentPackage, packageRelativePath.uptoSegment(1), modules); return createPackage(childPackage, packageRelativePath.removeFirstSegments(1), modules); } } private void removeObsoleteClassFiles(List<IFile> filesToRemove, IProject project) { if (filesToRemove.size() == 0) { return; } Set<File> moduleJars = new HashSet<File>(); for (IFile file : filesToRemove) { IPath filePath = file.getProjectRelativePath(); IPath sourceFolder = retrieveSourceFolder(filePath, project); if (sourceFolder == null) { return; } Package pkg = retrievePackage(file.getParent()); if (pkg == null) { return; } Module module = pkg.getModule(); TypeChecker typeChecker = typeCheckers.get(project); if (typeChecker == null) { return; } final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); boolean explodeModules = isExplodeModulesEnabled(project); final File ceylonOutputDirectory = explodeModules ? getCeylonClassesOutputDirectory(project) : null; File moduleDir = getModulePath(modulesOutputDirectory, module); //Remove the classes belonging to the source file from the //module archive and from the JDTClasses directory File moduleJar = new File(moduleDir, getModuleArchiveName(module)); if(moduleJar.exists()){ moduleJars.add(moduleJar); String relativeFilePath = filePath.makeRelativeTo(sourceFolder).toString(); try { List<String> entriesToDelete = new ArrayList<String>(); ZipFile zipFile = new ZipFile(moduleJar); Properties mapping = CarUtils.retrieveMappingFile(zipFile); for (String className : mapping.stringPropertyNames()) { String sourceFile = mapping.getProperty(className); if (relativeFilePath.equals(sourceFile)) { entriesToDelete.add(className); } } for (String entryToDelete : entriesToDelete) { zipFile.removeFile(entryToDelete); if (explodeModules) { new File(ceylonOutputDirectory, entryToDelete.replace('/', File.separatorChar)) .delete(); } } } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //Remove the source file from the source archive File moduleSrc = new File(moduleDir, getSourceArchiveName(module)); if(moduleSrc.exists()){ moduleJars.add(moduleSrc); String relativeFilePath = filePath.makeRelativeTo(sourceFolder).toString(); try { new ZipFile(moduleSrc).removeFile(relativeFilePath); } catch (ZipException e) { e.printStackTrace(); } } } final com.sun.tools.javac.util.Context dummyContext = new com.sun.tools.javac.util.Context(); class ConsoleLog implements Logger { PrintWriter writer; ConsoleLog() { writer = new PrintWriter(System.out); //new PrintWriter(getConsoleStream())); } @Override public void error(String str) { writer.append("Error: " + str + "\n"); } @Override public void warning(String str) { writer.append("Warning: " + str + "\n"); } @Override public void info(String str) { } @Override public void debug(String str) { } } ConsoleLog log = new ConsoleLog(); for (File moduleJar: moduleJars) { ShaSigner.sign(moduleJar, log, false); } } private static File getCeylonClassesOutputDirectory(IProject project) { return getCeylonClassesOutputFolder(project) .getRawLocation().toFile(); } public static IFolder getCeylonClassesOutputFolder(IProject project) { return project.getFolder(CEYLON_CLASSES_FOLDER_NAME); } public static boolean isInCeylonClassesOutputFolder(IPath path) { //TODO: this is crap! return path.lastSegment().equals(CEYLON_CLASSES_FOLDER_NAME); } public static File getCeylonModulesOutputDirectory(IProject project) { return getCeylonModulesOutputFolder(project).getRawLocation().toFile(); } public static IFolder getCeylonModulesOutputFolder(IProject project) { IPath path = CeylonProjectConfig.get(project).getOutputRepoPath(); return project.getFolder(path.removeFirstSegments(1)); } public static String getCeylonSystemRepo(IProject project) { String systemRepo = (String) getBuilderArgs(project).get("systemRepo"); if (systemRepo == null) { systemRepo = "${ceylon.repo}"; } return systemRepo; } public static String getInterpolatedCeylonSystemRepo(IProject project) { return interpolateVariablesInRepositoryPath(getCeylonSystemRepo(project)); } public static String[] getDefaultUserRepositories() { return new String[]{ "${ceylon.repo}", "${user.home}/.ceylon/repo", "http://modules.ceylon-lang.org/test" }; } public static String interpolateVariablesInRepositoryPath(String repoPath) { String userHomePath = System.getProperty("user.home"); String pluginRepoPath = CeylonPlugin.getInstance().getCeylonRepository().getAbsolutePath(); return repoPath.replace("${user.home}", userHomePath). replace("${ceylon.repo}", pluginRepoPath); } /** * String representation for debugging purposes */ public String toString() { return this.getProject() == null ? "CeylonBuilder for unknown project" : "CeylonBuilder for " + getProject().getName(); } }
package com.redhat.ceylon.eclipse.core.builder; import static com.redhat.ceylon.cmr.ceylon.CeylonUtils.repoManager; import static com.redhat.ceylon.compiler.java.util.Util.getModuleArchiveName; import static com.redhat.ceylon.compiler.java.util.Util.getModulePath; import static com.redhat.ceylon.compiler.java.util.Util.getSourceArchiveName; import static com.redhat.ceylon.compiler.typechecker.model.Module.LANGUAGE_MODULE_NAME; import static com.redhat.ceylon.eclipse.core.builder.CeylonNature.NATURE_ID; import static com.redhat.ceylon.eclipse.core.classpath.CeylonClasspathUtil.getCeylonClasspathContainers; import static com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile.createResourceVirtualFile; import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID; import static org.eclipse.core.resources.IResource.DEPTH_INFINITE; import static org.eclipse.core.resources.IResource.DEPTH_ZERO; import static org.eclipse.core.runtime.SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import javax.tools.DiagnosticListener; import javax.tools.FileObject; import javax.tools.JavaFileObject; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.antlr.runtime.CommonToken; import org.antlr.runtime.CommonTokenStream; import org.eclipse.core.internal.events.NotificationManager; import org.eclipse.core.resources.IBuildConfiguration; import org.eclipse.core.resources.IBuildContext; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.redhat.ceylon.cmr.api.ArtifactCallback; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.api.ArtifactResult; import com.redhat.ceylon.cmr.api.Logger; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.impl.ShaSigner; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.compiler.Options; import com.redhat.ceylon.compiler.java.codegen.CeylonCompilationUnit; import com.redhat.ceylon.compiler.java.codegen.CeylonFileObject; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.loader.UnknownTypeCollector; import com.redhat.ceylon.compiler.java.loader.mirror.JavacClass; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.CeyloncTaskImpl; import com.redhat.ceylon.compiler.java.tools.JarEntryFileObject; import com.redhat.ceylon.compiler.java.tools.LanguageCompiler; import com.redhat.ceylon.compiler.java.util.RepositoryLister; import com.redhat.ceylon.compiler.js.JsCompiler; import com.redhat.ceylon.compiler.loader.AbstractModelLoader; import com.redhat.ceylon.compiler.loader.ModelLoaderFactory; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleManager; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleValidator; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.context.ProducedTypeCache; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Modules; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Unit; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.Message; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError; import com.redhat.ceylon.compiler.typechecker.util.ModuleManagerFactory; import com.redhat.ceylon.eclipse.code.editor.CeylonTaskUtil; import com.redhat.ceylon.eclipse.core.classpath.CeylonLanguageModuleContainer; import com.redhat.ceylon.eclipse.core.classpath.CeylonProjectModulesContainer; import com.redhat.ceylon.eclipse.core.model.CeylonBinaryUnit; import com.redhat.ceylon.eclipse.core.model.IResourceAware; import com.redhat.ceylon.eclipse.core.model.JDTModelLoader; import com.redhat.ceylon.eclipse.core.model.JDTModule; import com.redhat.ceylon.eclipse.core.model.JDTModuleManager; import com.redhat.ceylon.eclipse.core.model.JavaCompilationUnit; import com.redhat.ceylon.eclipse.core.model.ModuleDependencies; import com.redhat.ceylon.eclipse.core.model.SourceFile; import com.redhat.ceylon.eclipse.core.model.mirror.JDTClass; import com.redhat.ceylon.eclipse.core.model.mirror.SourceClass; import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit; import com.redhat.ceylon.eclipse.core.vfs.IFileVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.IFolderVirtualFile; import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile; import com.redhat.ceylon.eclipse.ui.CeylonPlugin; import com.redhat.ceylon.eclipse.util.CarUtils; import com.redhat.ceylon.eclipse.util.CeylonSourceParser; import com.redhat.ceylon.eclipse.util.EclipseLogger; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent.Kind; import com.sun.source.util.TaskListener; import com.sun.tools.javac.file.RelativePath.RelativeFile; import com.sun.tools.javac.file.ZipFileIndexCache; /** * A builder may be activated on a file containing ceylon code every time it has * changed (when "Build automatically" is on), or when the programmer chooses to * "Build" a project. * * TODO This default implementation was generated from a template, it needs to * be completed manually. */ public class CeylonBuilder extends IncrementalProjectBuilder { public static final String CEYLON_CLASSES_FOLDER_NAME = ".exploded"; /** * Extension ID of the Ceylon builder, which matches the ID in the * corresponding extension definition in plugin.xml. */ public static final String BUILDER_ID = PLUGIN_ID + ".ceylonBuilder"; /** * A marker ID that identifies problems */ public static final String PROBLEM_MARKER_ID = PLUGIN_ID + ".ceylonProblem"; /** * A marker ID that identifies tasks */ public static final String TASK_MARKER_ID = PLUGIN_ID + ".ceylonTask"; public static final String SOURCE = "Ceylon"; private static final class CeylonModelCacheEnabler implements ProducedTypeCache.CacheEnabler { // Caches are disabled by default. And only enabled during build and warmup jobs private final ThreadLocal<Object> cachingIsEnabled = new ThreadLocal<>(); public CeylonModelCacheEnabler() { ProducedTypeCache.setCacheEnabler(this); } public void enableCaching() { cachingIsEnabled.set(new Object()); } public void disableCaching() { cachingIsEnabled.set(null); } public boolean isCacheEnabled() { return cachingIsEnabled.get() != null; } } private static CeylonModelCacheEnabler modelCacheEnabler = new CeylonModelCacheEnabler(); public static void doWithCeylonModelCaching(final Runnable action) { modelCacheEnabler.enableCaching(); try { action.run(); } finally { modelCacheEnabler.disableCaching(); } } public static <T> T doWithCeylonModelCaching(final Callable<T> action) throws CoreException { modelCacheEnabler.enableCaching(); try { return action.call(); } catch(CoreException ce) { throw ce; } catch(Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new RuntimeException(e); } } finally { modelCacheEnabler.disableCaching(); } } private final class BuildFileManager extends CeyloncFileManager { private final IProject project; final boolean explodeModules; private BuildFileManager(com.sun.tools.javac.util.Context context, boolean register, Charset charset, IProject project) { super(context, register, charset); this.project = project; explodeModules = isExplodeModulesEnabled(project); } @Override protected JavaFileObject getFileForOutput(Location location, final RelativeFile fileName, FileObject sibling) throws IOException { JavaFileObject javaFileObject = super.getFileForOutput(location, fileName, sibling); if (explodeModules && javaFileObject instanceof JarEntryFileObject && sibling instanceof CeylonFileObject) { final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); final File classFile = fileName.getFile(ceylonOutputDirectory); classFile.getParentFile().mkdirs(); return new ExplodingJavaFileObject(classFile, fileName, javaFileObject); } return javaFileObject; } @Override protected String getCurrentWorkingDir() { return project.getLocation().toFile().getAbsolutePath(); } } public static enum ModelState { Missing, Parsing, Parsed, TypeChecking, TypeChecked, Compiled }; final static Map<IProject, ModelState> modelStates = new HashMap<IProject, ModelState>(); private final static Map<IProject, TypeChecker> typeCheckers = new HashMap<IProject, TypeChecker>(); private final static Map<IProject, List<IFile>> projectSources = new HashMap<IProject, List<IFile>>(); private static Set<IProject> containersInitialized = new HashSet<IProject>(); private final static Map<IProject, RepositoryManager> projectRepositoryManagers = new HashMap<IProject, RepositoryManager>(); private final static Map<IProject, ModuleDependencies> projectModuleDependencies = new HashMap<IProject, ModuleDependencies>(); public static final String CEYLON_CONSOLE= "Ceylon Build"; //private long startTime; public static ModelState getModelState(IProject project) { ModelState modelState = modelStates.get(project); if (modelState == null) { return ModelState.Missing; } return modelState; } public static boolean isModelTypeChecked(IProject project) { ModelState modelState = getModelState(project); return modelState.ordinal() >= ModelState.TypeChecked.ordinal(); } public static boolean isModelParsed(IProject project) { ModelState modelState = getModelState(project); return modelState.ordinal() >= ModelState.Parsed.ordinal(); } public static List<PhasedUnit> getUnits(IProject project) { if (! isModelParsed(project)) { return Collections.emptyList(); } List<PhasedUnit> result = new ArrayList<PhasedUnit>(); TypeChecker tc = typeCheckers.get(project); if (tc!=null) { for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } return result; } public static List<PhasedUnit> getUnits() { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); for (IProject project : typeCheckers.keySet()) { if (isModelParsed(project)) { TypeChecker tc = typeCheckers.get(project); for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) { result.add(pu); } } } return result; } public static List<PhasedUnit> getUnits(String[] projects) { List<PhasedUnit> result = new ArrayList<PhasedUnit>(); if (projects!=null) { for (Map.Entry<IProject, TypeChecker> me: typeCheckers.entrySet()) { for (String pname: projects) { if (me.getKey().getName().equals(pname)) { IProject project = me.getKey(); if (isModelParsed(project)) { result.addAll(me.getValue().getPhasedUnits().getPhasedUnits()); } } } } } return result; } public String getBuilderID() { return BUILDER_ID; } public static boolean isCeylon(IFile file) { String ext = file.getFileExtension(); return ext!=null && ext.equals("ceylon"); } public static boolean isJava(IFile file) { return JavaCore.isJavaLikeFileName(file.getName()); } public static boolean isCeylonOrJava(IFile file) { return isCeylon(file) || isJava(file); } /** * Decide whether a file needs to be build using this builder. Note that * <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should * never return true for the same file. * * @return true iff an arbitrary file is a ceylon source file. */ protected boolean isSourceFile(IFile file) { if (!isCeylonOrJava(file)) { return false; } if (getRootFolder(file) == null) { return false; } return true; } public static JDTModelLoader getModelLoader(TypeChecker tc) { return (JDTModelLoader) ((JDTModuleManager) tc.getPhasedUnits() .getModuleManager()).getModelLoader(); } public static JDTModelLoader getProjectModelLoader(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return getModelLoader(typeChecker); } public final static class BooleanHolder { public boolean value; } public static class CeylonBuildHook { protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args, IProject javaProject, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException {} protected void deltasAnalyzed(List<IResourceDelta> currentDeltas, BooleanHolder sourceModified, BooleanHolder mustDoFullBuild, BooleanHolder mustResolveClasspathContainer, boolean mustContinueBuild) {} protected void resolvingClasspathContainer( List<IClasspathContainer> cpContainers) {} protected void setAndRefreshClasspathContainer() {} protected void doFullBuild() {} protected void parseCeylonModel() {} protected void doIncrementalBuild() {} protected void fullTypeCheckDuringIncrementalBuild() {} protected void incrementalBuildChangedSources(Set<IFile> changedSources) {} protected void incrementalBuildSources(Set<IFile> changedSources, List<IFile> filesToRemove, Collection<IFile> sourcesToCompile) {} protected void incrementalBuildResult(List<PhasedUnit> builtPhasedUnits) {} protected void beforeGeneratingBinaries() {} protected void afterGeneratingBinaries() {} protected void scheduleReentrantBuild() {} protected void afterReentrantBuild() {} protected void endBuild() {} }; public static final CeylonBuildHook noOpHook = new CeylonBuildHook(); public static final QualifiedName RESOURCE_PROPERTY_PACKAGE_MODEL = new QualifiedName(CeylonPlugin.PLUGIN_ID, "resourceProperty.packageModel"); public static final QualifiedName RESOURCE_PROPERTY_ROOT_FOLDER = new QualifiedName(CeylonPlugin.PLUGIN_ID, "resourceProperty.rootFolder"); private static CeylonBuildHook buildHook = new CeylonBuildHook() { List<CeylonBuildHook> contributedHooks = new LinkedList<>(); private synchronized void resetContributedHooks() { contributedHooks.clear(); for (IConfigurationElement confElement : Platform.getExtensionRegistry().getConfigurationElementsFor(CeylonPlugin.PLUGIN_ID + ".ceylonBuildHook")) { try { Object extension = confElement.createExecutableExtension("class"); if (extension instanceof ICeylonBuildHookProvider) { CeylonBuildHook hook = ((ICeylonBuildHookProvider) extension).getHook(); if (hook != null) { contributedHooks.add(hook); } } } catch (CoreException e) { e.printStackTrace(); } } } protected void startBuild(int kind, @SuppressWarnings("rawtypes") Map args, IProject javaProject, IBuildConfiguration config, IBuildContext context, IProgressMonitor monitor) throws CoreException { resetContributedHooks(); for (CeylonBuildHook hook : contributedHooks) { hook.startBuild(kind, args, javaProject, config, context, monitor); } } protected void deltasAnalyzed(List<IResourceDelta> currentDeltas, BooleanHolder sourceModified, BooleanHolder mustDoFullBuild, BooleanHolder mustResolveClasspathContainer, boolean mustContinueBuild) { for (CeylonBuildHook hook : contributedHooks) { hook.deltasAnalyzed(currentDeltas, sourceModified, mustDoFullBuild, mustResolveClasspathContainer, mustContinueBuild); } } protected void resolvingClasspathContainer( List<IClasspathContainer> cpContainers) { for (CeylonBuildHook hook : contributedHooks) { hook.resolvingClasspathContainer(cpContainers); } } protected void setAndRefreshClasspathContainer() { for (CeylonBuildHook hook : contributedHooks) { hook.setAndRefreshClasspathContainer(); } } protected void doFullBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.doFullBuild(); } } protected void parseCeylonModel() { for (CeylonBuildHook hook : contributedHooks) { hook.parseCeylonModel(); } } protected void doIncrementalBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.doIncrementalBuild(); } } protected void fullTypeCheckDuringIncrementalBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.fullTypeCheckDuringIncrementalBuild(); } } protected void incrementalBuildChangedSources(Set<IFile> changedSources) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildChangedSources(changedSources); } } protected void incrementalBuildSources(Set<IFile> changedSources, List<IFile> filesToRemove, Collection<IFile> sourcesToCompile) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildSources(changedSources, filesToRemove, sourcesToCompile); } } protected void incrementalBuildResult(List<PhasedUnit> builtPhasedUnits) { for (CeylonBuildHook hook : contributedHooks) { hook.incrementalBuildResult(builtPhasedUnits); } } protected void beforeGeneratingBinaries() { for (CeylonBuildHook hook : contributedHooks) { hook.beforeGeneratingBinaries(); } } protected void afterGeneratingBinaries() { for (CeylonBuildHook hook : contributedHooks) { hook.afterGeneratingBinaries(); } } protected void scheduleReentrantBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.beforeGeneratingBinaries(); } } protected void afterReentrantBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.afterReentrantBuild(); } } protected void endBuild() { for (CeylonBuildHook hook : contributedHooks) { hook.endBuild(); } } }; public static CeylonBuildHook replaceHook(CeylonBuildHook hook){ CeylonBuildHook previousHook = buildHook; buildHook = hook; return previousHook; } private static WeakReference<Job> notificationJobReference = null; private static synchronized Job getNotificationJob() { Job job = null; if (notificationJobReference != null) { job = notificationJobReference.get(); } if (job == null) { for (Job j : Job.getJobManager().find(null)) { if (NotificationManager.class.equals(j.getClass().getEnclosingClass())) { job = j; notificationJobReference = new WeakReference<Job>(job); break; } } } return job; } public static void waitForUpToDateJavaModel(long timeout, IProject project, IProgressMonitor monitor) { Job job = getNotificationJob(); if (job == null) { return; } monitor.subTask("Taking in account the resource changes of the previous builds" + project != null ? project.getName() : ""); long timeLimit = System.currentTimeMillis() + timeout; while (job.getState() != Job.NONE) { boolean stopWaiting = false; if (job.isBlocking()) { stopWaiting = true; } try { Thread.sleep(1000); } catch (InterruptedException e) { stopWaiting = true; } if (System.currentTimeMillis() > timeLimit) { stopWaiting = true; } if (stopWaiting) { break; } } } @Override protected IProject[] build(final int kind, @SuppressWarnings("rawtypes") Map args, IProgressMonitor mon) throws CoreException { final IProject project = getProject(); final IJavaProject javaProject = JavaCore.create(project); final SubMonitor monitor = SubMonitor.convert(mon, "Ceylon build of project " + project.getName(), 100); try { buildHook.startBuild(kind, args, project, getBuildConfig(), getContext(), monitor); } catch (CoreException e) { if (e.getStatus().getSeverity() == IStatus.CANCEL) { return project.getReferencedProjects(); } } try { IMarker[] buildMarkers = project.findMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); for (IMarker m: buildMarkers) { Object message = m.getAttribute("message"); if (message!=null && message.toString().endsWith("'JDTClasses'")) { //ignore message from JDT about missing JDTClasses dir m.delete(); } else if (message!=null && message.toString().contains("is missing required Java project:")) { return project.getReferencedProjects(); } } List<IClasspathContainer> cpContainers = getCeylonClasspathContainers(javaProject); boolean languageModuleContainerFound = false; boolean applicationModulesContainerFound = false; for (IClasspathContainer container : cpContainers) { if (container instanceof CeylonLanguageModuleContainer) { languageModuleContainerFound = true; } if (container instanceof CeylonProjectModulesContainer) { applicationModulesContainerFound = true; } } if (! languageModuleContainerFound) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon classpath container for the language module is not set on the project " + project.getName() + " (try running Enable Ceylon Builder on the project)"); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } if (! applicationModulesContainerFound) { //if the ClassPathContainer is missing, add an error IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon classpath container for application modules is not set on the project " + project.getName() + " (try running Enable Ceylon Builder on the project)"); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } /* Begin issue #471 */ ICommand[] builders = project.getDescription().getBuildSpec(); int javaOrder=0, ceylonOrder = 0; for (int n=0; n<builders.length; n++) { if (builders[n].getBuilderName().equals(JavaCore.BUILDER_ID)) { javaOrder = n; } else if (builders[n].getBuilderName().equals(CeylonBuilder.BUILDER_ID)) { ceylonOrder = n; } } if (ceylonOrder < javaOrder) { //if the build order is not correct, add an error and return IMarker marker = project.createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER); marker.setAttribute(IMarker.MESSAGE, "The Ceylon Builder should run after the Java Builder. Change order of builders in project properties for project: " + project.getName()); marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.LOCATION, "Bytecode generation"); return project.getReferencedProjects(); } /* End issue #471 */ List<PhasedUnit> builtPhasedUnits = Collections.emptyList(); final BooleanHolder mustDoFullBuild = new BooleanHolder(); final BooleanHolder mustResolveClasspathContainer = new BooleanHolder(); final IResourceDelta currentDelta = getDelta(project); List<IResourceDelta> projectDeltas = new ArrayList<IResourceDelta>(); projectDeltas.add(currentDelta); for (IProject requiredProject : project.getReferencedProjects()) { projectDeltas.add(getDelta(requiredProject)); } boolean somethingToDo = chooseBuildTypeFromDeltas(kind, project, projectDeltas, mustDoFullBuild, mustResolveClasspathContainer); if (!somethingToDo && (args==null || !args.containsKey(BUILDER_ID + ".reentrant"))) { return project.getReferencedProjects(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (mustResolveClasspathContainer.value) { if (cpContainers != null) { buildHook.resolvingClasspathContainer(cpContainers); for (IClasspathContainer container: cpContainers) { if (container instanceof CeylonProjectModulesContainer) { CeylonProjectModulesContainer applicationModulesContainer = (CeylonProjectModulesContainer) container; boolean changed = applicationModulesContainer.resolveClasspath(monitor.newChild(19, PREPEND_MAIN_LABEL_TO_SUBTASK), true); if(changed) { buildHook.setAndRefreshClasspathContainer(); JavaCore.setClasspathContainer(applicationModulesContainer.getPath(), new IJavaProject[]{javaProject}, new IClasspathContainer[]{null} , monitor); applicationModulesContainer.refreshClasspathContainer(monitor); } } } } } boolean mustWarmupCompletionProcessor = false; final TypeChecker typeChecker; Collection<IFile> sourcesForBinaryGeneration = Collections.emptyList(); if (mustDoFullBuild.value) { buildHook.doFullBuild(); monitor.setTaskName("Full Ceylon build of project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing existing markers of project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, true); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } //if (! getModelState(project).equals(ModelState.Parsed)) { if (!mustResolveClasspathContainer.value) { monitor.subTask("Parsing source of project " + project.getName()); //if we already resolved the classpath, the //model has already been freshly-parsed buildHook.parseCeylonModel(); typeChecker = parseCeylonModel(project, monitor.newChild(19, PREPEND_MAIN_LABEL_TO_SUBTASK)); } else { typeChecker = getProjectTypeChecker(project); } monitor.setWorkRemaining(80); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Typechecking all source files of project " + project.getName()); modelStates.put(project, ModelState.TypeChecking); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return fullTypeCheck(project, typeChecker, monitor.newChild(30, PREPEND_MAIN_LABEL_TO_SUBTASK )); } }); modelStates.put(project, ModelState.TypeChecked); sourcesForBinaryGeneration = getProjectSources(project); mustWarmupCompletionProcessor = true; } else { buildHook.doIncrementalBuild(); typeChecker = typeCheckers.get(project); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); List<IFile> filesToRemove = new ArrayList<IFile>(); Set<IFile> changedSources = new HashSet<IFile>(); monitor.subTask("Scanning deltas of project " + project.getName()); calculateChangedSources(currentDelta, projectDeltas, filesToRemove, getProjectSources(project), changedSources, monitor); monitor.worked(4); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Cleaning removed files for project " + project.getName()); cleanRemovedSources(filesToRemove, phasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (!isModelTypeChecked(project)) { buildHook.fullTypeCheckDuringIncrementalBuild(); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Clearing existing markers of project (except backend errors)" + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, false); monitor.worked(1); monitor.subTask("Initial typechecking all source files of project " + project.getName()); modelStates.put(project, ModelState.TypeChecking); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return fullTypeCheck(project, typeChecker, monitor.newChild(22, PREPEND_MAIN_LABEL_TO_SUBTASK )); } }); modelStates.put(project, ModelState.TypeChecked); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Collecting dependencies of project " + project.getName()); // getConsoleStream().println(timedMessage("Collecting dependencies")); collectDependencies(project, typeChecker, builtPhasedUnits); monitor.worked(1); monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(builtPhasedUnits, project); monitor.worked(1); mustWarmupCompletionProcessor = true; } monitor.setWorkRemaining(70); monitor.subTask("Incremental Ceylon build of project " + project.getName()); monitor.subTask("Scanning dependencies of deltas of project " + project.getName()); final Collection<IFile> sourceToCompile= new HashSet<IFile>(); calculateDependencies(project, sourceToCompile, currentDelta, changedSources, typeChecker, phasedUnits, monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.incrementalBuildSources(changedSources, filesToRemove, sourceToCompile); monitor.subTask("Compiling " + sourceToCompile.size() + " source files in project " + project.getName()); builtPhasedUnits = doWithCeylonModelCaching(new Callable<List<PhasedUnit>>() { @Override public List<PhasedUnit> call() throws Exception { return incrementalBuild(project, sourceToCompile, monitor.newChild(19, PREPEND_MAIN_LABEL_TO_SUBTASK)); } }); if (builtPhasedUnits.isEmpty() && sourceToCompile.isEmpty()) { if (mustWarmupCompletionProcessor) { warmupCompletionProcessor(project, typeChecker); } return project.getReferencedProjects(); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.incrementalBuildResult(builtPhasedUnits); sourcesForBinaryGeneration = sourceToCompile; } monitor.setWorkRemaining(50); monitor.subTask("Collecting problems for project " + project.getName()); addProblemAndTaskMarkers(builtPhasedUnits, project); monitor.worked(1); if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("Collecting dependencies of project " + project.getName()); // getConsoleStream().println(timedMessage("Collecting dependencies")); collectDependencies(project, typeChecker, builtPhasedUnits); monitor.worked(4); if (monitor.isCanceled()) { throw new OperationCanceledException(); } buildHook.beforeGeneratingBinaries(); monitor.subTask("Generating binaries for project " + project.getName()); final Collection<IFile> sourcesToProcess = sourcesForBinaryGeneration; doWithCeylonModelCaching(new Callable<Boolean>() { @Override public Boolean call() throws CoreException { return generateBinaries(project, javaProject, sourcesToProcess, typeChecker, monitor.newChild(45, PREPEND_MAIN_LABEL_TO_SUBTASK)); } }); buildHook.afterGeneratingBinaries(); if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (isExplodeModulesEnabled(project)) { monitor.subTask("Rebuilding using exploded modules directory of " + project.getName()); sheduleIncrementalRebuild(args, project, monitor); } if (mustWarmupCompletionProcessor) { warmupCompletionProcessor(project, typeChecker); } return project.getReferencedProjects(); } finally { monitor.done(); buildHook.endBuild(); } } private void warmupCompletionProcessor(final IProject project, final TypeChecker typeChecker) { Job job = new WarmupJob(project.getName(), typeChecker); job.setPriority(Job.BUILD); //job.setSystem(true); job.setRule(project.getWorkspace().getRoot()); job.schedule(); } private void sheduleIncrementalRebuild(@SuppressWarnings("rawtypes") Map args, final IProject project, IProgressMonitor monitor) { try { getCeylonClassesOutputFolder(project).refreshLocal(DEPTH_INFINITE, monitor); } catch (CoreException e) { e.printStackTrace(); }//monitor); if (args==null || !args.containsKey(BUILDER_ID + ".reentrant")) { buildHook.scheduleReentrantBuild(); final CeylonBuildHook currentBuildHook = buildHook; Job job = new Job("Rebuild with Ceylon classes") { @Override protected IStatus run(IProgressMonitor monitor) { try { //we have already done a build of both the Java and Ceylon classes //so now go back and try to build the both the Java and Ceylon //classes again, using the classes we previously generated - this //is to allow references from Java to Ceylon project.build(INCREMENTAL_BUILD, JavaCore.BUILDER_ID, null, monitor); Map<String,String> map = new HashMap<String,String>(); map.put(BUILDER_ID + ".reentrant", "true"); project.build(INCREMENTAL_BUILD, BUILDER_ID, map, monitor); currentBuildHook.afterReentrantBuild(); } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }; job.setRule(project.getWorkspace().getRoot()); job.schedule(); } } private void collectDependencies(IProject project, TypeChecker typeChecker, List<PhasedUnit> builtPhasedUnits) throws CoreException { for (PhasedUnit pu : builtPhasedUnits) { new UnitDependencyVisitor(pu).visit(pu.getCompilationUnit()); } } private void cleanRemovedSources(List<IFile> filesToRemove, PhasedUnits phasedUnits, IProject project) { removeObsoleteClassFiles(filesToRemove, project); for (IFile fileToRemove: filesToRemove) { if(isCeylon(fileToRemove)) { // Remove the ceylon phasedUnit (which will also remove the unit from the package) PhasedUnit phasedUnitToDelete = phasedUnits.getPhasedUnit(createResourceVirtualFile(fileToRemove)); if (phasedUnitToDelete != null) { assert(phasedUnitToDelete instanceof ProjectPhasedUnit); ((ProjectPhasedUnit) phasedUnitToDelete).remove(); } } else if (isJava(fileToRemove)) { // Remove the external unit from the package Package pkg = getPackage((IFolder)fileToRemove.getParent()); if (pkg != null) { for (Unit unitToTest: pkg.getUnits()) { if (unitToTest.getFilename().equals(fileToRemove.getName())) { pkg.removeUnit(unitToTest); assert (pkg.getModule() instanceof JDTModule); JDTModule module = (JDTModule) pkg.getModule(); module.removedOriginalUnit(unitToTest.getRelativePath()); break; } } } } } } private void calculateDependencies(IProject project, Collection<IFile> sourceToCompile, IResourceDelta currentDelta, Set<IFile> fChangedSources, TypeChecker typeChecker, PhasedUnits phasedUnits, IProgressMonitor monitor) { if (!fChangedSources.isEmpty()) { Collection<IFile> changeDependents= new HashSet<IFile>(); changeDependents.addAll(fChangedSources); /*if (emitDiags) { getConsoleStream().println("Changed files:"); dumpSourceList(changeDependents); }*/ boolean changed = false; do { Collection<IFile> additions= new HashSet<IFile>(); for (Iterator<IFile> iter=changeDependents.iterator(); iter.hasNext();) { IFile srcFile= iter.next(); IProject currentFileProject = srcFile.getProject(); TypeChecker currentFileTypeChecker = null; if (currentFileProject == project) { currentFileTypeChecker = typeChecker; } else { currentFileTypeChecker = getProjectTypeChecker(currentFileProject); } Set<String> filesDependingOn = getDependentsOf(srcFile, currentFileTypeChecker, currentFileProject); for (String dependingFile: filesDependingOn) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } //TODO: note that the following is slightly // fragile - it depends on the format // of the path that we use to track // dependents! IPath pathRelativeToProject = new Path(dependingFile); //.makeRelativeTo(project.getLocation()); IFile depFile= (IFile) project.findMember(pathRelativeToProject); if (depFile == null) { depFile= (IFile) currentFileProject.findMember(dependingFile); } if (depFile != null) { additions.add(depFile); } else { System.err.println("could not resolve dependent unit: " + dependingFile); } } } changed = changeDependents.addAll(additions); } while (changed); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnits.getPhasedUnits()) { Unit unit = phasedUnit.getUnit(); if (!unit.getUnresolvedReferences().isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } } Set<Declaration> duplicateDeclarations = unit.getDuplicateDeclarations(); if (!duplicateDeclarations.isEmpty()) { IFile fileToAdd = ((IFileVirtualFile)(phasedUnit.getUnitFile())).getFile(); if (fileToAdd.exists()) { sourceToCompile.add(fileToAdd); } for (Declaration duplicateDeclaration : duplicateDeclarations) { Unit duplicateUnit = duplicateDeclaration.getUnit(); if ((duplicateUnit instanceof SourceFile) && (duplicateUnit instanceof IResourceAware)) { IFile duplicateDeclFile = ((IResourceAware) duplicateUnit).getFileResource(); if (duplicateDeclFile != null && duplicateDeclFile.exists()) { sourceToCompile.add(duplicateDeclFile); } } } } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (IFile f: changeDependents) { if (isSourceFile(f) && f.getProject() == project) { if (f.exists()) { sourceToCompile.add(f); } else { // If the file is moved : add a dependency on the new file if (currentDelta != null) { IResourceDelta removedFile = currentDelta.findMember(f.getProjectRelativePath()); if (removedFile != null && (removedFile.getFlags() & IResourceDelta.MOVED_TO) != 0 && removedFile.getMovedToPath() != null) { sourceToCompile.add(project.getFile(removedFile.getMovedToPath().removeFirstSegments(1))); } } } } } } } private void calculateChangedSources(final IResourceDelta currentDelta, List<IResourceDelta> projectDeltas, final List<IFile> filesToRemove, final List<IFile> currentProjectSources, final Set<IFile> changedSources, IProgressMonitor monitor) throws CoreException { for (final IResourceDelta projectDelta: projectDeltas) { if (projectDelta != null) { final IProject project = (IProject) projectDelta.getResource(); List<IFolder> projectSourceFolders = getSourceFolders(project); List<IFolder> projectResourceFolders = getResourceFolders(project); for (IResourceDelta projectAffectedChild: projectDelta.getAffectedChildren()) { if (! (projectAffectedChild.getResource() instanceof IFolder)) { continue; } final IFolder rootFolder = (IFolder) projectAffectedChild.getResource(); boolean isSourceDirectory = false; boolean isResourceDirectory = false; for (IFolder sourceFolder: projectSourceFolders) { if (projectAffectedChild.getResource().getFullPath().isPrefixOf(sourceFolder.getFullPath())) { isSourceDirectory = true; break; } } for (IFolder resourceFolder: projectResourceFolders) { if (projectAffectedChild.getResource().getFullPath().isPrefixOf(resourceFolder.getFullPath())) { isSourceDirectory = true; break; } } if (isResourceDirectory || isSourceDirectory) { // a real Ceylon source or resource folder so scan for changes projectAffectedChild.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { IResource resource = delta.getResource(); if (resource instanceof IFile) { IFile file= (IFile) resource; if (isCeylonOrJava(file)) { changedSources.add(file); if (projectDelta == currentDelta) { if (delta.getKind() == IResourceDelta.REMOVED) { filesToRemove.add((IFile) resource); currentProjectSources.remove((IFile) resource); } if (delta.getKind() == IResourceDelta.ADDED) { IFile addedFile = (IFile) resource; int index = currentProjectSources.indexOf(addedFile); if ((index >= 0)) { currentProjectSources.remove(index); } currentProjectSources.add(addedFile); } } } return false; } if (resource instanceof IFolder) { IFolder folder= (IFolder) resource; if (projectDelta == currentDelta) { if (folder.exists() && delta.getKind() != IResourceDelta.REMOVED) { if (getPackage(folder) == null || getRootFolder(folder) == null) { IContainer parent = folder.getParent(); if (parent instanceof IFolder) { Package parentPkg = getPackage((IFolder)parent); if (parentPkg != null) { Package pkg = getProjectModelLoader(project).findOrCreatePackage(parentPkg.getModule(), parentPkg.getNameAsString() + "." + folder.getName()); resource.setSessionProperty(CeylonBuilder.RESOURCE_PROPERTY_PACKAGE_MODEL, new WeakReference<Package>(pkg)); resource.setSessionProperty(CeylonBuilder.RESOURCE_PROPERTY_ROOT_FOLDER, rootFolder); } } } } } } return true; } }); } } } } } public boolean chooseBuildTypeFromDeltas(final int kind, final IProject project, final List<IResourceDelta> currentDeltas, final BooleanHolder mustDoFullBuild, final BooleanHolder mustResolveClasspathContainer) { mustDoFullBuild.value = kind == FULL_BUILD || kind == CLEAN_BUILD || !isModelParsed(project); mustResolveClasspathContainer.value = kind==FULL_BUILD; //false; final BooleanHolder sourceModified = new BooleanHolder(); if (JavaProjectStateMirror.hasClasspathChanged(project)) { mustDoFullBuild.value = true; } if (!mustDoFullBuild.value || !mustResolveClasspathContainer.value) { for (IResourceDelta currentDelta: currentDeltas) { if (currentDelta != null) { try { currentDelta.accept(new DeltaScanner(mustDoFullBuild, project, sourceModified, mustResolveClasspathContainer)); } catch (CoreException e) { e.printStackTrace(); mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } else { mustDoFullBuild.value = true; mustResolveClasspathContainer.value = true; } } } class DecisionMaker { public boolean mustContinueBuild() { return mustDoFullBuild.value || mustResolveClasspathContainer.value || sourceModified.value || ! isModelTypeChecked(project); } }; DecisionMaker decisionMaker = new DecisionMaker(); buildHook.deltasAnalyzed(currentDeltas, sourceModified, mustDoFullBuild, mustResolveClasspathContainer, decisionMaker.mustContinueBuild()); return decisionMaker.mustContinueBuild(); } // private static String successMessage(boolean binariesGenerationOK) { // return " " + (binariesGenerationOK ? // "...binary generation succeeded" : "...binary generation FAILED"); private Set<String> getDependentsOf(IFile srcFile, TypeChecker currentFileTypeChecker, IProject currentFileProject) { if (srcFile.getRawLocation().getFileExtension().equals("ceylon")) { PhasedUnit phasedUnit = currentFileTypeChecker.getPhasedUnits() .getPhasedUnit(ResourceVirtualFile.createResourceVirtualFile(srcFile)); if (phasedUnit != null && phasedUnit.getUnit() != null) { return phasedUnit.getUnit().getDependentsOf(); } } else { Unit unit = getJavaUnit(currentFileProject, srcFile); if (unit instanceof JavaCompilationUnit) { return unit.getDependentsOf(); } } return Collections.emptySet(); } static ProjectPhasedUnit parseFileToPhasedUnit(final ModuleManager moduleManager, final TypeChecker typeChecker, final ResourceVirtualFile file, final ResourceVirtualFile srcDir, final Package pkg) { return new CeylonSourceParser<ProjectPhasedUnit>() { @Override protected String getCharset() { try { return file.getResource().getProject().getDefaultCharset(); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override protected ProjectPhasedUnit createPhasedUnit(CompilationUnit cu, Package pkg, CommonTokenStream tokenStream) { return new ProjectPhasedUnit(file, srcDir, cu, pkg, moduleManager, typeChecker, tokenStream.getTokens()); } }.parseFileToPhasedUnit(moduleManager, typeChecker, file, srcDir, pkg); } private List<PhasedUnit> incrementalBuild(IProject project, Collection<IFile> sourceToCompile, IProgressMonitor mon) { SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + sourceToCompile.size() + " source files in project " + project.getName(), sourceToCompile.size()*6); TypeChecker typeChecker = typeCheckers.get(project); PhasedUnits pus = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) pus.getModuleManager(); JDTModelLoader modelLoader = getModelLoader(typeChecker); // First refresh the modules that are cross-project references to sources modules // in referenced projects. This will : // - clean the binary declarations and reload the class-to-source mapping file for binary-based modules, // - remove old PhasedUnits and parse new or updated PhasedUnits from the source archive for source-based modules for (Module m : typeChecker.getContext().getModules().getListOfModules()) { if (m instanceof JDTModule) { JDTModule module = (JDTModule) m; if (module.isCeylonArchive()) { module.refresh(); } } } // Secondly typecheck again the changed PhasedUnits in changed external source modules // (those which come from referenced projects) List<PhasedUnits> phasedUnitsOfDependencies = typeChecker.getPhasedUnitsOfDependencies(); List<PhasedUnit> dependencies = new ArrayList<PhasedUnit>(); for (PhasedUnits phasedUnits: phasedUnitsOfDependencies) { for (PhasedUnit phasedUnit: phasedUnits.getPhasedUnits()) { dependencies.add(phasedUnit); } } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.scanDeclarations(); monitor.worked(1); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning type declarations " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } for (PhasedUnit pu: dependencies) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } // Then typecheck the changed source of this project Set<String> cleanedPackages = new HashSet<String>(); List<PhasedUnit> phasedUnitsToUpdate = new ArrayList<PhasedUnit>(); for (IFile fileToUpdate : sourceToCompile) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } // skip non-ceylon files if(!isCeylon(fileToUpdate)) { if (isJava(fileToUpdate)) { Unit toRemove = getJavaUnit(project, fileToUpdate); if(toRemove != null) { // If the unit is not null, the package should never be null Package p = toRemove.getPackage(); p.removeUnit(toRemove); assert (p.getModule() instanceof JDTModule); JDTModule module = (JDTModule) p.getModule(); module.removedOriginalUnit(toRemove.getRelativePath()); } else { String packageName = getPackageName(fileToUpdate); if (! cleanedPackages.contains(packageName)) { modelLoader.clearCachesOnPackage(packageName); cleanedPackages.add(packageName); } } } continue; } ResourceVirtualFile file = ResourceVirtualFile.createResourceVirtualFile(fileToUpdate); IFolder srcFolder = getRootFolder(fileToUpdate); ProjectPhasedUnit alreadyBuiltPhasedUnit = (ProjectPhasedUnit) pus.getPhasedUnit(file); Package pkg = null; if (alreadyBuiltPhasedUnit!=null) { // Editing an already built file pkg = alreadyBuiltPhasedUnit.getPackage(); } else { IFolder packageFolder = (IFolder) file.getResource().getParent(); pkg = getPackage(packageFolder); } if (srcFolder == null || pkg == null) { continue; } ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolder.getProjectRelativePath()); PhasedUnit newPhasedUnit = parseFileToPhasedUnit(moduleManager, typeChecker, file, srcDir, pkg); phasedUnitsToUpdate.add(newPhasedUnit); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } if (phasedUnitsToUpdate.size() == 0) { return phasedUnitsToUpdate; } clearProjectMarkers(project); clearMarkersOn(sourceToCompile, true); for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { assert(phasedUnit instanceof ProjectPhasedUnit); ((ProjectPhasedUnit)phasedUnit).install(); } modelLoader.setupSourceFileObjects(phasedUnitsToUpdate); if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { phasedUnit.validateTree(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanDeclarations(); } monitor.worked(1); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isTypeDeclarationsScanned()) { monitor.subTask("- scanning type declarations " + phasedUnit.getUnit().getFilename()); phasedUnit.scanTypeDeclarations(); } monitor.worked(2); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isRefinementValidated()) { phasedUnit.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { if (! phasedUnit.isFullyTyped()) { monitor.subTask("- typechecking " + phasedUnit.getUnit().getFilename()); phasedUnit.analyseTypes(); if (showWarnings(project)) { phasedUnit.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit phasedUnit : phasedUnitsToUpdate) { phasedUnit.analyseFlow(); } UnknownTypeCollector utc = new UnknownTypeCollector(); for (PhasedUnit pu : phasedUnitsToUpdate) { pu.getCompilationUnit().visit(utc); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.done(); return phasedUnitsToUpdate; } private Unit getJavaUnit(IProject project, IFile fileToUpdate) { IJavaElement javaElement = (IJavaElement) fileToUpdate.getAdapter(IJavaElement.class); if (javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IJavaElement packageFragment = compilationUnit.getParent(); JDTModelLoader projectModelLoader = getProjectModelLoader(project); // TODO : Why not use the Model Loader cache to get the declaration // instead of iterating through all the packages ? if (projectModelLoader != null) { Package pkg = projectModelLoader.findPackage(packageFragment.getElementName()); if (pkg != null) { for (Declaration decl : pkg.getMembers()) { Unit unit = decl.getUnit(); if (unit.getFilename().equals(fileToUpdate.getName())) { return unit; } } } } } return null; } private List<PhasedUnit> fullTypeCheck(IProject project, TypeChecker typeChecker, IProgressMonitor mon) throws CoreException { List<PhasedUnits> phasedUnitsOfDependencies = typeChecker.getPhasedUnitsOfDependencies(); List<PhasedUnit> dependencies = new ArrayList<PhasedUnit>(); for (PhasedUnits phasedUnits: phasedUnitsOfDependencies) { for (PhasedUnit phasedUnit: phasedUnits.getPhasedUnits()) { dependencies.add(phasedUnit); } } final List<PhasedUnit> listOfUnits = typeChecker.getPhasedUnits().getPhasedUnits(); SubMonitor monitor = SubMonitor.convert(mon, "Typechecking " + listOfUnits.size() + " source files of project " + project.getName(), dependencies.size()*5+listOfUnits.size()*6); monitor.subTask("- typechecking source archives for project " + project.getName()); JDTModelLoader loader = getModelLoader(typeChecker); // loader.reset(); for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.scanDeclarations(); monitor.worked(1); } for (PhasedUnit pu: dependencies) { monitor.subTask("- scanning type declarations " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } for (PhasedUnit pu: dependencies) { pu.validateRefinement(); //TODO: only needed for type hierarchy view in IDE! } Module languageModule = loader.getLanguageModule(); loader.loadPackage(languageModule, "com.redhat.ceylon.compiler.java.metadata", true); loader.loadPackage(languageModule, LANGUAGE_MODULE_NAME, true); loader.loadPackage(languageModule, "ceylon.language.descriptor", true); loader.loadPackageDescriptors(); monitor.subTask("(typechecking source files for project " + project.getName() +")"); for (PhasedUnit pu : listOfUnits) { if (! pu.isDeclarationsScanned()) { monitor.subTask("- scanning declarations " + pu.getUnit().getFilename()); pu.validateTree(); pu.scanDeclarations(); monitor.worked(1); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isTypeDeclarationsScanned()) { monitor.subTask("- scanning types " + pu.getUnit().getFilename()); pu.scanTypeDeclarations(); monitor.worked(2); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { if (! pu.isRefinementValidated()) { pu.validateRefinement(); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu : listOfUnits) { if (! pu.isFullyTyped()) { monitor.subTask("- typechecking " + pu.getUnit().getFilename()); pu.analyseTypes(); if (showWarnings(project)) { pu.analyseUsage(); } monitor.worked(3); } } if (monitor.isCanceled()) { throw new OperationCanceledException(); } for (PhasedUnit pu: listOfUnits) { pu.analyseFlow(); } UnknownTypeCollector utc = new UnknownTypeCollector(); for (PhasedUnit pu : listOfUnits) { pu.getCompilationUnit().visit(utc); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } projectModuleDependencies.get(project).addModulesWithDependencies(typeChecker.getContext().getModules().getListOfModules()); monitor.done(); return typeChecker.getPhasedUnits().getPhasedUnits(); } public static TypeChecker parseCeylonModel(final IProject project, final IProgressMonitor mon) throws CoreException { return doWithCeylonModelCaching(new Callable<TypeChecker>() { @Override public TypeChecker call() throws CoreException { SubMonitor monitor = SubMonitor.convert(mon, "Setting up typechecker for project " + project.getName(), 113); modelStates.put(project, ModelState.Parsing); typeCheckers.remove(project); projectRepositoryManagers.remove(project); projectSources.remove(project); if (projectModuleDependencies.containsKey(project)) { projectModuleDependencies.get(project).reset(); } else { projectModuleDependencies.put(project, new ModuleDependencies()); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } final IJavaProject javaProject = JavaCore.create(project); TypeChecker typeChecker = buildTypeChecker(project, javaProject); PhasedUnits phasedUnits = typeChecker.getPhasedUnits(); JDTModuleManager moduleManager = (JDTModuleManager) phasedUnits.getModuleManager(); moduleManager.setTypeChecker(typeChecker); Context context = typeChecker.getContext(); JDTModelLoader modelLoader = (JDTModelLoader) moduleManager.getModelLoader(); Module defaultModule = context.getModules().getDefaultModule(); monitor.worked(1); monitor.subTask("- parsing source files for project " + project.getName()); if (monitor.isCanceled()) { throw new OperationCanceledException(); } phasedUnits.getModuleManager().prepareForTypeChecking(); List<IFile> scannedSources = scanSources(project, javaProject, typeChecker, phasedUnits, moduleManager, modelLoader, defaultModule, monitor.newChild(10)); if (monitor.isCanceled()) { throw new OperationCanceledException(); } modelLoader.setupSourceFileObjects(typeChecker.getPhasedUnits().getPhasedUnits()); monitor.worked(1); // Parsing of ALL units in the source folder should have been done if (monitor.isCanceled()) { throw new OperationCanceledException(); } monitor.subTask("- determining module dependencies for " + project.getName()); phasedUnits.visitModules(); //By now the language module version should be known (as local) //or we should use the default one. Module languageModule = context.getModules().getLanguageModule(); if (languageModule.getVersion() == null) { languageModule.setVersion(TypeChecker.LANGUAGE_MODULE_VERSION); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } final ModuleValidator moduleValidator = new ModuleValidator(context, phasedUnits) { @Override protected void executeExternalModulePhases() {} @Override protected Exception catchIfPossible(Exception e) { if (e instanceof OperationCanceledException) { throw (OperationCanceledException)e; } return e; } }; final int maxModuleValidatorWork = 100000; final SubMonitor validatorProgress = SubMonitor.convert(monitor.newChild(100), maxModuleValidatorWork); moduleValidator.setListener(new ModuleValidator.ProgressListener() { @Override public void retrievingModuleArtifact(final Module module, final ArtifactContext artifactContext) { final long numberOfModulesNotAlreadySearched = moduleValidator.numberOfModulesNotAlreadySearched(); final long totalNumberOfModules = numberOfModulesNotAlreadySearched + moduleValidator.numberOfModulesAlreadySearched(); final long oneModuleWork = maxModuleValidatorWork / totalNumberOfModules; final int workRemaining = (int) ((double)numberOfModulesNotAlreadySearched * oneModuleWork); validatorProgress.setWorkRemaining(workRemaining); artifactContext.setCallback(new ArtifactCallback() { SubMonitor artifactProgress = null; long size; long alreadyDownloaded = 0; StringBuilder messageBuilder = new StringBuilder("- downloading module ") .append(module.getSignature()) .append(' '); @Override public void start(String nodeFullPath, long size, String contentStore) { this.size = size; int ticks = size > 0 ? (int) size : 100000; artifactProgress = SubMonitor.convert(validatorProgress.newChild((int)oneModuleWork), ticks); if (! contentStore.isEmpty()) { messageBuilder.append("from ").append(contentStore); } artifactProgress.subTask(messageBuilder.toString()); if (artifactProgress.isCanceled()) { throw new OperationCanceledException("Interrupted the download of module : " + module.getSignature()); } } @Override public void read(byte[] bytes, int length) { if (artifactProgress.isCanceled()) { throw new OperationCanceledException("Interrupted the download of module : " + module.getSignature()); } if (size < 0) { artifactProgress.setWorkRemaining(length*100); } else { artifactProgress.subTask(new StringBuilder(messageBuilder) .append(" ( ") .append(alreadyDownloaded * 100 / size) .append("% )").toString()); } alreadyDownloaded += length; artifactProgress.worked(length); } @Override public void error(File localFile, Throwable t) { localFile.delete(); artifactProgress.setWorkRemaining(0); } @Override public void done(File arg0) { artifactProgress.setWorkRemaining(0); } }); } @Override public void resolvingModuleArtifact(Module module, ArtifactResult artifactResult) { long numberOfModulesNotAlreadySearched = moduleValidator.numberOfModulesNotAlreadySearched(); validatorProgress.setWorkRemaining((int) (numberOfModulesNotAlreadySearched * 100 / (numberOfModulesNotAlreadySearched + moduleValidator.numberOfModulesAlreadySearched()))); validatorProgress.subTask(new StringBuilder("- resolving module ") .append(module.getSignature()) .toString()); } }); moduleValidator.verifyModuleDependencyTree(); validatorProgress.setWorkRemaining(0); typeChecker.setPhasedUnitsOfDependencies(moduleValidator.getPhasedUnitsOfDependencies()); for (PhasedUnits dependencyPhasedUnits: typeChecker.getPhasedUnitsOfDependencies()) { modelLoader.addSourceArchivePhasedUnits(dependencyPhasedUnits.getPhasedUnits()); } modelLoader.setModuleAndPackageUnits(); if (compileToJs(project)) { for (Module module : typeChecker.getContext().getModules().getListOfModules()) { if (module instanceof JDTModule) { JDTModule jdtModule = (JDTModule) module; if (jdtModule.isCeylonArchive()) { getProjectRepositoryManager(project).getArtifact( new ArtifactContext( jdtModule.getNameAsString(), jdtModule.getVersion(), ArtifactContext.JS)); } } } } monitor.worked(1); typeCheckers.put(project, typeChecker); projectSources.put(project, scannedSources); modelStates.put(project, ModelState.Parsed); monitor.done(); return typeChecker; } }); } private static TypeChecker buildTypeChecker(IProject project, final IJavaProject javaProject) throws CoreException { TypeCheckerBuilder typeCheckerBuilder = new TypeCheckerBuilder() .verbose(false) .moduleManagerFactory(new ModuleManagerFactory(){ @Override public ModuleManager createModuleManager(Context context) { return new JDTModuleManager(context, javaProject); } }); RepositoryManager repositoryManager = getProjectRepositoryManager(project); typeCheckerBuilder.setRepositoryManager(repositoryManager); TypeChecker typeChecker = typeCheckerBuilder.getTypeChecker(); return typeChecker; } private static List<IFile> scanSources(IProject project, IJavaProject javaProject, final TypeChecker typeChecker, final PhasedUnits phasedUnits, final JDTModuleManager moduleManager, final JDTModelLoader modelLoader, final Module defaultModule, IProgressMonitor mon) throws CoreException { SubMonitor monitor = SubMonitor.convert(mon, 10000); final List<IFile> scannedSources = new ArrayList<IFile>(); final Collection<IPath> sourceFolders = getSourceFolders(javaProject); for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final ResourceVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } // First Scan all non-default source modules and attach the contained packages srcDirResource.accept(new ModulesScanner(defaultModule, modelLoader, moduleManager, srcDir, srcFolderPath, typeChecker, monitor)); } for (final IPath srcAbsoluteFolderPath : sourceFolders) { final IPath srcFolderPath = srcAbsoluteFolderPath.makeRelativeTo(project.getFullPath()); final IFolderVirtualFile srcDir = new IFolderVirtualFile(project, srcFolderPath); IResource srcDirResource = srcDir.getResource(); if (! srcDirResource.exists()) { continue; } if (monitor.isCanceled()) { throw new OperationCanceledException(); } // Then scan all source files srcDirResource.accept(new SourceScanner(defaultModule, modelLoader, moduleManager, srcDir, srcFolderPath, typeChecker, scannedSources, phasedUnits, monitor)); } return scannedSources; } private static void addProblemAndTaskMarkers(final List<PhasedUnit> units, final IProject project) { for (PhasedUnit phasedUnit: units) { IFile file = getFile(phasedUnit); phasedUnit.getCompilationUnit().visit(new MarkerCreator(file)); addTaskMarkers(file, phasedUnit.getTokens()); } } private boolean generateBinaries(IProject project, IJavaProject javaProject, Collection<IFile> filesToCompile, TypeChecker typeChecker, IProgressMonitor monitor) throws CoreException { List<String> options = new ArrayList<String>(); List<String> js_srcdir = new ArrayList<String>(); List<String> js_repos = new ArrayList<String>(); boolean js_verbose = false; String js_outRepo = null; String srcPath = ""; for (IPath sourceFolder : getSourceFolders(javaProject)) { File sourcePathElement = toFile(project,sourceFolder .makeRelativeTo(project.getFullPath())); if (! srcPath.isEmpty()) { srcPath += File.pathSeparator; } srcPath += sourcePathElement.getAbsolutePath(); js_srcdir.add(sourcePathElement.getAbsolutePath()); } options.add("-src"); options.add(srcPath); String resPath = ""; CeylonProjectConfig config = CeylonProjectConfig.get(project); for (String resourceFolder : config.getResourceDirectories()) { if (!resPath.isEmpty()) { resPath += File.pathSeparator; } resPath += resourceFolder; } options.add("-res"); options.add(resPath); options.add("-encoding"); options.add(project.getDefaultCharset()); for (String repository : getUserRepositories(project)) { options.add("-rep"); options.add(repository); js_repos.add(repository); } String verbose = System.getProperty("ceylon.verbose"); if (verbose!=null && "true".equals(verbose)) { options.add("-verbose"); js_verbose = true; } options.add("-g:lines,vars,source"); String systemRepo = getInterpolatedCeylonSystemRepo(project); if(systemRepo != null && !systemRepo.isEmpty()){ options.add("-sysrep"); options.add(systemRepo); } final File modulesOutputDir = getCeylonModulesOutputDirectory(project); if (modulesOutputDir!=null) { options.add("-out"); options.add(modulesOutputDir.getAbsolutePath()); js_outRepo = modulesOutputDir.getAbsolutePath(); } List<File> javaSourceFiles = new ArrayList<File>(); List<File> sourceFiles = new ArrayList<File>(); List<File> moduleFiles = new ArrayList<File>(); for (IFile file : filesToCompile) { if(isCeylon(file)) { sourceFiles.add(file.getRawLocation().toFile()); if (file.getName().equals(ModuleManager.MODULE_FILE)) { moduleFiles.add(file.getRawLocation().toFile()); } } else if(isJava(file)) javaSourceFiles.add(file.getRawLocation().toFile()); } PrintWriter printWriter = new PrintWriter(System.out);//(getConsoleErrorStream(), true); boolean success = true; //Compile JS first if (!sourceFiles.isEmpty() && compileToJs(project)) { success = compileJs(project, typeChecker, js_srcdir, js_repos, js_verbose, js_outRepo, printWriter, ! compileToJava(project)); } if ((!sourceFiles.isEmpty() || !javaSourceFiles.isEmpty()) && compileToJava(project)) { // For Java don't stop compiling when encountering errors options.add("-continue"); // always add the java files, otherwise ceylon code won't see them // and they won't end up in the archives (src/car) sourceFiles.addAll(javaSourceFiles); if (!sourceFiles.isEmpty()){ success = success & compile(project, javaProject, options, sourceFiles, typeChecker, printWriter, monitor); } } return success; } private boolean compileJs(IProject project, TypeChecker typeChecker, List<String> js_srcdir, List<String> js_repos, boolean js_verbose, String js_outRepo, PrintWriter printWriter, boolean generateSourceArchive) throws CoreException { Options jsopts = new Options() .repos(js_repos) .sources(js_srcdir) .systemRepo(getInterpolatedCeylonSystemRepo(project)) .outDir(js_outRepo) .optimize(true) .verbose(js_verbose ? "all" : null) .generateSourceArchive(generateSourceArchive) .encoding(project.getDefaultCharset()) .offline(CeylonProjectConfig.get(project).isOffline()); JsCompiler jsc = new JsCompiler(typeChecker, jsopts) { @Override protected boolean nonCeylonUnit(Unit u) { if (! super.nonCeylonUnit(u)) { return false; } if (u instanceof CeylonBinaryUnit) { CeylonBinaryUnit ceylonBinaryUnit = (CeylonBinaryUnit) u; if (ceylonBinaryUnit.getCeylonSourceRelativePath() != null) { return false; } } return true; } public String getFullPath(PhasedUnit pu) { VirtualFile virtualFile = pu.getUnitFile(); if (virtualFile instanceof ResourceVirtualFile) { return ((IFileVirtualFile) virtualFile).getFile().getLocation().toOSString(); } else { return virtualFile.getPath(); } }; }.stopOnErrors(false); try { if (!jsc.generate()) { CompileErrorReporter errorReporter = null; //Report backend errors for (Message e : jsc.getErrors()) { if (e instanceof UnexpectedError) { if (errorReporter == null) { errorReporter = new CompileErrorReporter(project); } errorReporter.report(new CeylonCompilationError(project, (UnexpectedError)e)); } } if (errorReporter != null) { //System.out.println("Ceylon-JS compiler failed for " + project.getName()); errorReporter.failed(); } return false; } else { //System.out.println("compile ok to js"); return true; } } catch (IOException ex) { ex.printStackTrace(printWriter); return false; } } @SuppressWarnings("deprecation") private boolean compile(final IProject project, IJavaProject javaProject, List<String> options, java.util.List<File> sourceFiles, final TypeChecker typeChecker, PrintWriter printWriter, IProgressMonitor mon) throws VerifyError { int numberOfJavaFiles = 0; int numberOfCeylonFiles = 0; for (File file : sourceFiles) { if (JavaCore.isJavaLikeFileName(file.getName())) { numberOfJavaFiles ++; } else if (file.getName().endsWith(".ceylon")){ numberOfCeylonFiles ++; } } int numberOfSourceFiles = numberOfCeylonFiles + numberOfJavaFiles; final SubMonitor monitor = SubMonitor.convert(mon, "Generating binaries for " + numberOfSourceFiles + " source files in project " + project.getName(), numberOfSourceFiles * 2); com.redhat.ceylon.compiler.java.tools.CeyloncTool compiler; try { compiler = new com.redhat.ceylon.compiler.java.tools.CeyloncTool(); } catch (VerifyError e) { System.err.println("ERROR: Cannot run tests! Did you maybe forget to configure the -Xbootclasspath/p: parameter?"); throw e; } CompileErrorReporter errorReporter = new CompileErrorReporter(project); final com.sun.tools.javac.util.Context context = new com.sun.tools.javac.util.Context(); context.put(com.sun.tools.javac.util.Log.outKey, printWriter); context.put(DiagnosticListener.class, errorReporter); CeylonLog.preRegister(context); BuildFileManager fileManager = new BuildFileManager(context, true, null, project); computeCompilerClasspath(project, javaProject, options); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles); if (reuseEclipseModelInCompilation(project)) { setupJDTModelLoader(project, typeChecker, context); } ZipFileIndexCache.getSharedInstance().clearCache(); CeyloncTaskImpl task = (CeyloncTaskImpl) compiler.getTask(printWriter, fileManager, errorReporter, options, null, compilationUnits); task.setTaskListener(new TaskListener() { @Override public void started(TaskEvent ta) { if (! ta.getKind().equals(Kind.PARSE) && ! ta.getKind().equals(Kind.ANALYZE)) { return; } String name = ta.getSourceFile().getName(); name = name.substring(name.lastIndexOf("/")+1); if (ta.getKind().equals(Kind.PARSE)) { CompilationUnitTree cut = ta.getCompilationUnit(); if (cut != null && cut instanceof CeylonCompilationUnit) { monitor.subTask("- transforming " + name); } else { monitor.subTask("- parsing " + name); } } if (ta.getKind().equals(Kind.ANALYZE)) { monitor.subTask("- generating bytecode for " + name); } } @Override public void finished(TaskEvent ta) { if (! ta.getKind().equals(Kind.PARSE) && ! ta.getKind().equals(Kind.ANALYZE)) { return; } monitor.worked(1); } }); boolean success=false; try { success = task.call(); } catch (Exception e) { e.printStackTrace(printWriter); } if (!success) { errorReporter.failed(); } monitor.done(); return success; } private void computeCompilerClasspath(IProject project, IJavaProject javaProject, List<String> options) { List<String> classpathElements = new ArrayList<String>(); // Modules projectModules = getProjectModules(project); // ArtifactContext ctx; // if (projectModules != null) { // Module languageModule = projectModules.getLanguageModule(); // ctx = new ArtifactContext(languageModule.getNameAsString(), // languageModule.getVersion()); // else { // ctx = new ArtifactContext(LANGUAGE_MODULE_NAME, // TypeChecker.LANGUAGE_MODULE_VERSION); // ctx.setSuffix(ArtifactContext.CAR); // RepositoryManager repositoryManager = getProjectRepositoryManager(project); // if (repositoryManager!=null) { // //try { // File languageModuleArchive = repositoryManager.getArtifact(ctx); // classpathElements.add(languageModuleArchive.getAbsolutePath()); // /*} // catch (Exception e) { // e.printStackTrace(); // }*/ addProjectClasspathElements(classpathElements, javaProject); try { for (IProject p: project.getReferencedProjects()) { if(p.isAccessible()){ addProjectClasspathElements(classpathElements, JavaCore.create(p)); } } } catch (CoreException ce) { ce.printStackTrace(); } options.add("-classpath"); // add the compiletime required jars (those used by the language module implicitely) classpathElements.addAll(CeylonPlugin.getCompiletimeRequiredJars()); String classpath = ""; for (String cpElement : classpathElements) { if (! classpath.isEmpty()) { classpath += File.pathSeparator; } classpath += cpElement; } options.add(classpath); } private void setupJDTModelLoader(final IProject project, final TypeChecker typeChecker, final com.sun.tools.javac.util.Context context) { final JDTModelLoader modelLoader = getModelLoader(typeChecker); context.put(LanguageCompiler.ceylonContextKey, typeChecker.getContext()); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(LanguageCompiler.compilerDelegateKey, new JdtCompilerDelegate(modelLoader, project, typeChecker, context)); context.put(TypeFactory.class, modelLoader.getTypeFactory()); context.put(ModelLoaderFactory.class, new ModelLoaderFactory() { @Override public AbstractModelLoader createModelLoader( com.sun.tools.javac.util.Context context) { return modelLoader; } }); } private void addProjectClasspathElements(List<String> classpathElements, IJavaProject javaProj) { try { List<IClasspathContainer> containers = getCeylonClasspathContainers(javaProj); for (IClasspathContainer container : containers) { for (IClasspathEntry cpEntry : container.getClasspathEntries()) { if (!isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(cpEntry.getPath().toOSString()); } } } File outputDir = toFile(javaProj.getProject(), javaProj.getOutputLocation() .makeRelativeTo(javaProj.getProject().getFullPath())); classpathElements.add(outputDir.getAbsolutePath()); for (IClasspathEntry cpEntry : javaProj.getResolvedClasspath(true)) { if (isInCeylonClassesOutputFolder(cpEntry.getPath())) { classpathElements.add(javaProj.getProject().getLocation().append(cpEntry.getPath().lastSegment()).toOSString()); } } } catch (JavaModelException e1) { e1.printStackTrace(); } } public static boolean isExplodeModulesEnabled(IProject project) { Map<String,String> args = getBuilderArgs(project); return args.get("explodeModules")!=null || args.get("enableJdtClasses")!=null; } public static boolean compileWithJDTModel = true; public static boolean reuseEclipseModelInCompilation(IProject project) { return loadDependenciesFromModelLoaderFirst(project) && compileWithJDTModel; } // Keep it false on master until we fix the associated cross-reference and search issues // by correctly managing source to binary links and indexes public static boolean loadBinariesFirst = "true".equals(System.getProperty("ceylon.loadBinariesFirst", "true")); public static boolean loadDependenciesFromModelLoaderFirst(IProject project) { return compileToJava(project) && loadBinariesFirst; } public static boolean showWarnings(IProject project) { return getBuilderArgs(project).get("hideWarnings")==null; } public static boolean compileToJs(IProject project) { return getBuilderArgs(project).get("compileJs")!=null; } public static boolean compileToJava(IProject project) { return CeylonNature.isEnabled(project) && getBuilderArgs(project).get("compileJava")==null; } public static String fileName(ClassMirror c) { if (c instanceof JavacClass) { return ((JavacClass) c).classSymbol.classfile.getName(); } else if (c instanceof JDTClass) { return ((JDTClass) c).getFileName(); } else if (c instanceof SourceClass) { return ((SourceClass) c).getModelDeclaration().getUnit().getFilename(); } else { return "another file"; } } public static List<String> getUserRepositories(IProject project) throws CoreException { List<String> userRepos = getCeylonRepositories(project); userRepos.addAll(getReferencedProjectsOutputRepositories(project)); return userRepos; } public static List<String> getAllRepositories(IProject project) throws CoreException { List<String> allRepos = getUserRepositories(project); allRepos.add(CeylonProjectConfig.get(project).getMergedRepositories().getCacheRepository().getUrl()); return allRepos; } public static List<String> getReferencedProjectsOutputRepositories(IProject project) throws CoreException { List<String> repos = new ArrayList<String>(); if (project != null) { for (IProject referencedProject: project.getReferencedProjects()) { if (referencedProject.isOpen() && referencedProject.hasNature(NATURE_ID)) { repos.add(getCeylonModulesOutputDirectory(referencedProject).getAbsolutePath()); } } } return repos; } private static Map<String,String> getBuilderArgs(IProject project) { if (project!=null) { try { for (ICommand c: project.getDescription().getBuildSpec()) { if (c.getBuilderName().equals(BUILDER_ID)) { return c.getArguments(); } } } catch (CoreException e) { e.printStackTrace(); } } return Collections.emptyMap(); } public static List<String> getCeylonRepositories(IProject project) { CeylonProjectConfig projectConfig = CeylonProjectConfig.get(project); List<String> projectLookupRepos = projectConfig.getProjectLocalRepos(); List<String> globalLookupRepos = projectConfig.getGlobalLookupRepos(); List<String> projectRemoteRepos = projectConfig.getProjectRemoteRepos(); List<String> otherRemoteRepos = projectConfig.getOtherRemoteRepos(); List<String> repos = new ArrayList<String>(); repos.addAll(projectLookupRepos); repos.addAll(globalLookupRepos); repos.addAll(projectRemoteRepos); repos.addAll(otherRemoteRepos); return repos; } private static File toFile(IProject project, IPath path) { return project.getFolder(path).getRawLocation().toFile(); } private static void clearMarkersOn(IResource resource, boolean alsoDeleteBackendErrors) { try { resource.deleteMarkers(TASK_MARKER_ID, false, DEPTH_INFINITE); resource.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_INFINITE); if (alsoDeleteBackendErrors) { resource.deleteMarkers(PROBLEM_MARKER_ID + ".backend", true, DEPTH_INFINITE); } //these are actually errors from the Ceylon compiler, but //we did not bother creating a separate annotation type! resource.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_INFINITE); } catch (CoreException e) { e.printStackTrace(); } } private static void clearProjectMarkers(IProject project) { try { //project.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, true, DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID, true, DEPTH_ZERO); project.deleteMarkers(PROBLEM_MARKER_ID + ".backend", true, DEPTH_ZERO); } catch (CoreException e) { e.printStackTrace(); } } private static void clearMarkersOn(Collection<IFile> files, boolean alsoDeleteBackendErrors) { for(IFile file: files) { clearMarkersOn(file, alsoDeleteBackendErrors); } } /*private void dumpSourceList(Collection<IFile> sourcesToCompile) { MessageConsoleStream consoleStream= getConsoleStream(); for(Iterator<IFile> iter= sourcesToCompile.iterator(); iter.hasNext(); ) { IFile srcFile= iter.next(); consoleStream.println(" " + srcFile.getFullPath()); } }*/ // protected static MessageConsoleStream getConsoleStream() { // return findConsole().newMessageStream(); // protected static MessageConsoleStream getConsoleErrorStream() { // final MessageConsoleStream stream = findConsole().newMessageStream(); // //TODO: all this, just to get the color red? can that be right?? // /*try { // getWorkbench().getProgressService().runInUI(getWorkbench().getWorkbenchWindows()[0], // new IRunnableWithProgress() { // // @Override // public void run(IProgressMonitor monitor) throws InvocationTargetException, // InterruptedException { // stream.setColor(getWorkbench().getDisplay().getSystemColor(SWT.COLOR_RED)); // } // }, null); // } // catch (Exception e) { // e.printStackTrace(); // }*/ // return stream; // private String timedMessage(String message) { // long elapsedTimeMs = (System.nanoTime() - startTime) / 1000000; // return String.format("[%1$10d] %2$s", elapsedTimeMs, message); // /** // * Find or create the console with the given name // * @param consoleName // */ // protected static MessageConsole findConsole() { // String consoleName = CEYLON_CONSOLE; // MessageConsole myConsole= null; // final IConsoleManager consoleManager= ConsolePlugin.getDefault().getConsoleManager(); // IConsole[] consoles= consoleManager.getConsoles(); // for(int i= 0; i < consoles.length; i++) { // IConsole console= consoles[i]; // if (console.getName().equals(consoleName)) // myConsole= (MessageConsole) console; // if (myConsole == null) { // myConsole= new MessageConsole(consoleName, // CeylonPlugin.getInstance().getImageRegistry() // .getDescriptor(CeylonResources.BUILDER)); // consoleManager.addConsoles(new IConsole[] { myConsole }); //// consoleManager.showConsoleView(myConsole); // return myConsole; private static void addTaskMarkers(IFile file, List<CommonToken> tokens) { // clearTaskMarkersOn(file); for (CommonToken token : tokens) { if (token.getType() == CeylonLexer.LINE_COMMENT || token.getType() == CeylonLexer.MULTI_COMMENT) { CeylonTaskUtil.addTaskMarkers(token, file); } } } @Override protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); IProject project = getProject(); // startTime = System.nanoTime(); // getConsoleStream().println(timedMessage("Starting Ceylon clean on project: " + project.getName())); cleanupModules(monitor, project); cleanupJdtClasses(monitor, project); monitor.subTask("Clearing project and source markers for project " + project.getName()); clearProjectMarkers(project); clearMarkersOn(project, true); // getConsoleStream().println(timedMessage("End Ceylon clean on project: " + project.getName())); } private void cleanupJdtClasses(IProgressMonitor monitor, IProject project) { if (isExplodeModulesEnabled(project)) { monitor.subTask("Cleaning exploded modules directory of project " + project.getName()); final File ceylonOutputDirectory = getCeylonClassesOutputDirectory(project); new RepositoryLister(Arrays.asList(".*")).list(ceylonOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(ceylonOutputDirectory)) { path.delete(); } } }); } } private void cleanupModules(IProgressMonitor monitor, IProject project) { final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); if (modulesOutputDirectory != null) { monitor.subTask("Cleaning existing artifacts of project " + project.getName()); List<String> extensionsToDelete = Arrays.asList(".jar", ".car", ".src", ".sha1"); new RepositoryLister(extensionsToDelete).list(modulesOutputDirectory, new RepositoryLister.Actions() { @Override public void doWithFile(File path) { path.delete(); } public void exitDirectory(File path) { if (path.list().length == 0 && !path.equals(modulesOutputDirectory)) { path.delete(); } } }); } } public static IFile getFile(PhasedUnit phasedUnit) { return ((IFileVirtualFile) phasedUnit.getUnitFile()).getFile(); } // TODO think: doRefresh(file.getParent()); // N.B.: Assumes all // generated files go into parent folder private static List<IFile> getProjectSources(IProject project) { return projectSources.get(project); } public static TypeChecker getProjectTypeChecker(IProject project) { return typeCheckers.get(project); } public static Modules getProjectModules(IProject project) { TypeChecker typeChecker = getProjectTypeChecker(project); if (typeChecker == null) { return null; } return typeChecker.getContext().getModules(); } public static List<Module> getModulesInProject(IProject project) { List<Module> moduleList = new ArrayList<Module>(); Modules modules = getProjectModules(project); if (modules != null) { IJavaProject javaProject = JavaCore.create(project); for (Module module : modules.getListOfModules()) { if (!module.isDefault() && !module.isJava()) { try { for (IPackageFragment pkg : javaProject.getPackageFragments()) { if (pkg.getKind()==IPackageFragmentRoot.K_SOURCE) { if (!pkg.isReadOnly() && pkg.getElementName().equals(module.getNameAsString())) { moduleList.add(module); } } } } catch (JavaModelException e) { e.printStackTrace(); } } } } return moduleList; } public static RepositoryManager getProjectRepositoryManager(IProject project) { RepositoryManager repoManager = projectRepositoryManagers.get(project); if (repoManager == null) { try { repoManager = resetProjectRepositoryManager(project); } catch(CoreException e) { e.printStackTrace(); } } return repoManager; } public static RepositoryManager resetProjectRepositoryManager(IProject project) throws CoreException { RepositoryManager repositoryManager = repoManager() .offline(CeylonProjectConfig.get(project).isOffline()) .cwd(project.getLocation().toFile()) .systemRepo(getInterpolatedCeylonSystemRepo(project)) .extraUserRepos(getReferencedProjectsOutputRepositories(project)) .logger(new EclipseLogger()) .isJDKIncluded(true) .buildManager(); projectRepositoryManagers.put(project, repositoryManager); return repositoryManager; } public static Iterable<IProject> getProjects() { return typeCheckers.keySet(); } public static Iterable<TypeChecker> getTypeCheckers() { return typeCheckers.values(); } public static void removeProject(IProject project) { typeCheckers.remove(project); projectSources.remove(project); modelStates.remove(project); containersInitialized.remove(project); projectRepositoryManagers.remove(project); CeylonProjectConfig.remove(project); JavaProjectStateMirror.cleanup(project); projectModuleDependencies.remove(project); } public static List<IFolder> getSourceFolders(IProject project) { //TODO: is the call to JavaCore.create() very expensive?? List<IPath> folderPaths = getSourceFolders(JavaCore.create(project)); List<IFolder> sourceFolders = new ArrayList<>(folderPaths.size()); for (IPath path : folderPaths) { IResource r = project.findMember(path.makeRelativeTo(project.getFullPath())); if (r instanceof IFolder) { sourceFolders.add((IFolder) r); } } return sourceFolders; } /** * Read the IJavaProject classpath configuration and populate the ISourceProject's * build path accordingly. */ public static List<IPath> getSourceFolders(IJavaProject javaProject) { if (javaProject.exists()) { try { List<IPath> projectSourceFolders = new ArrayList<IPath>(); for (IClasspathEntry entry: javaProject.getRawClasspath()) { IPath path = entry.getPath(); if (isCeylonSourceEntry(entry)) { projectSourceFolders.add(path); } } return projectSourceFolders; } catch (JavaModelException e) { e.printStackTrace(); } } return Collections.emptyList(); } public static List<IFolder> getResourceFolders(IProject project) { LinkedList<IFolder> resourceFolers = new LinkedList<>(); if (project.exists()) { for (String resourceFolder : CeylonProjectConfig.get(project).getResourceDirectories()) { if (resourceFolder.startsWith("." + File.separator)) { resourceFolder = project.getLocation().toOSString() + resourceFolder.substring(1); } IPath resourceDirFullPath = Path.fromOSString(resourceFolder); IPath projectLocation = project.getLocation(); if (projectLocation.isPrefixOf(resourceDirFullPath)) { resourceFolers.add(project.getFolder(resourceDirFullPath.makeRelativeTo(projectLocation))); } } } return resourceFolers; } public static List<IFolder> getRootFolders(IProject project) { LinkedList<IFolder> rootFolders = new LinkedList<>(); rootFolders.addAll(getSourceFolders(project)); rootFolders.addAll(getResourceFolders(project)); return rootFolders; } public static boolean isCeylonSourceEntry(IClasspathEntry entry) { if (entry.getEntryKind()!=IClasspathEntry.CPE_SOURCE) { return false; } for (IPath exclusionPattern : entry.getExclusionPatterns()) { if (exclusionPattern.toString().endsWith(".ceylon")) { return false; } } return true; } public static IFolder getRootFolder(IFolder folder) { Object property = null; if (! folder.exists()) { for (IFolder sourceFolder: getSourceFolders(folder.getProject())) { if (sourceFolder.getFullPath().isPrefixOf(folder.getFullPath())) { return sourceFolder; } } for (IFolder resourceFolder: getResourceFolders(folder.getProject())) { if (resourceFolder.getFullPath().isPrefixOf(folder.getFullPath())) { return resourceFolder; } } return null; } try { property = folder.getSessionProperty(RESOURCE_PROPERTY_ROOT_FOLDER); } catch (CoreException e) { CeylonPlugin.getInstance().getLog().log(new Status(Status.WARNING, CeylonPlugin.PLUGIN_ID, "Unexpected exception", e)); } if (property instanceof IFolder) { return (IFolder) property; } return null; } public static IFolder getRootFolder(IFile file) { if (file.getParent() instanceof IFolder) { return getRootFolder((IFolder) file.getParent()); } return null; } public static String getPackageName(IResource resource) { if (resource instanceof IFolder) { return getPackage((IFolder) resource).getQualifiedNameString(); } if (resource instanceof IFile) { return getPackage((IFile) resource).getQualifiedNameString(); } return null; } public static Package getPackage(IFolder resource) { Object property = null; if (! resource.exists()) { IFolder rootFolder = getRootFolder(resource); if (rootFolder != null) { IPath rootRelativePath = resource.getFullPath().makeRelativeTo(rootFolder.getFullPath()); JDTModelLoader modelLoader = getProjectModelLoader(resource.getProject()); if (modelLoader != null) { return modelLoader.findPackage(Util.formatPath(Arrays.asList(rootRelativePath.segments()), '.')); } } return null; } try { property = resource.getSessionProperty(RESOURCE_PROPERTY_PACKAGE_MODEL); } catch (CoreException e) { CeylonPlugin.getInstance().getLog().log(new Status(Status.WARNING, CeylonPlugin.PLUGIN_ID, "Unexpected exception", e)); } if (property instanceof WeakReference<?>) { Object pkg = ((WeakReference<?>) property).get(); if (pkg instanceof Package) { return (Package) pkg; } } return null; } public static Package getPackage(IFile file) { if (file.getParent() instanceof IFolder) { return getPackage((IFolder) file.getParent()); } return null; } private void removeObsoleteClassFiles(List<IFile> filesToRemove, IProject project) { if (filesToRemove.size() == 0) { return; } Set<File> moduleJars = new HashSet<File>(); for (IFile file : filesToRemove) { IPath filePath = file.getProjectRelativePath(); IFolder rootFolder = getRootFolder(file); if (rootFolder == null) { return; } IPath rootFolderProjectRelativePath = rootFolder.getProjectRelativePath(); Package pkg = getPackage((IFolder)file.getParent()); if (pkg == null) { return; } Module module = pkg.getModule(); TypeChecker typeChecker = typeCheckers.get(project); if (typeChecker == null) { return; } final File modulesOutputDirectory = getCeylonModulesOutputDirectory(project); boolean explodeModules = isExplodeModulesEnabled(project); final File ceylonOutputDirectory = explodeModules ? getCeylonClassesOutputDirectory(project) : null; File moduleDir = getModulePath(modulesOutputDirectory, module); //Remove the classes belonging to the source file from the //module archive and from the JDTClasses directory File moduleJar = new File(moduleDir, getModuleArchiveName(module)); if(moduleJar.exists()){ moduleJars.add(moduleJar); String relativeFilePath = filePath.makeRelativeTo(rootFolderProjectRelativePath).toString(); try { List<String> entriesToDelete = new ArrayList<String>(); ZipFile zipFile = new ZipFile(moduleJar); Properties mapping = CarUtils.retrieveMappingFile(zipFile); for (String className : mapping.stringPropertyNames()) { String sourceFile = mapping.getProperty(className); if (relativeFilePath.equals(sourceFile)) { entriesToDelete.add(className); } } for (String entryToDelete : entriesToDelete) { zipFile.removeFile(entryToDelete); if (explodeModules) { new File(ceylonOutputDirectory, entryToDelete.replace('/', File.separatorChar)) .delete(); } } } catch (ZipException e) { e.printStackTrace(); } } //Remove the source file from the source archive File moduleSrc = new File(moduleDir, getSourceArchiveName(module)); if(moduleSrc.exists()){ moduleJars.add(moduleSrc); String relativeFilePath = filePath.makeRelativeTo(rootFolderProjectRelativePath).toString(); try { new ZipFile(moduleSrc).removeFile(relativeFilePath); } catch (ZipException e) { e.printStackTrace(); } } } // final com.sun.tools.javac.util.Context dummyContext = new com.sun.tools.javac.util.Context(); class ConsoleLog implements Logger { PrintWriter writer; ConsoleLog() { writer = new PrintWriter(System.out); //new PrintWriter(getConsoleStream())); } @Override public void error(String str) { writer.println("Error: " + str); } @Override public void warning(String str) { writer.println("Warning: " + str); } @Override public void info(String str) { } @Override public void debug(String str) { } } ConsoleLog log = new ConsoleLog(); for (File moduleJar: moduleJars) { ShaSigner.sign(moduleJar, log, false); } } private static File getCeylonClassesOutputDirectory(IProject project) { return getCeylonClassesOutputFolder(project) .getRawLocation().toFile(); } public static IFolder getCeylonClassesOutputFolder(IProject project) { return project.getFolder(CEYLON_CLASSES_FOLDER_NAME); } public static boolean isInCeylonClassesOutputFolder(IPath path) { //TODO: this is crap! return path.lastSegment().equals(CEYLON_CLASSES_FOLDER_NAME); } public static File getCeylonModulesOutputDirectory(IProject project) { return getCeylonModulesOutputFolder(project).getRawLocation().toFile(); } public static IFolder getCeylonModulesOutputFolder(IProject project) { IPath path = CeylonProjectConfig.get(project).getOutputRepoPath(); return project.getFolder(path.removeFirstSegments(1)); } public static String getCeylonSystemRepo(IProject project) { String systemRepo = (String) getBuilderArgs(project).get("systemRepo"); if (systemRepo == null) { systemRepo = "${ceylon.repo}"; } return systemRepo; } public static String getInterpolatedCeylonSystemRepo(IProject project) { return interpolateVariablesInRepositoryPath(getCeylonSystemRepo(project)); } public static String[] getDefaultUserRepositories() { return new String[]{ "${ceylon.repo}", "${user.home}/.ceylon/repo", Constants.REPO_URL_CEYLON }; } public static String interpolateVariablesInRepositoryPath(String repoPath) { String userHomePath = System.getProperty("user.home"); String pluginRepoPath = CeylonPlugin.getInstance().getCeylonRepository().getAbsolutePath(); return repoPath.replace("${user.home}", userHomePath). replace("${ceylon.repo}", pluginRepoPath); } /** * String representation for debugging purposes */ public String toString() { return this.getProject() == null ? "CeylonBuilder for unknown project" : "CeylonBuilder for " + getProject().getName(); } public static void setContainerInitialized(IProject project) { containersInitialized.add(project); } public static boolean isContainerInitialized(IProject project) { return containersInitialized.contains(project); } public static boolean allClasspathContainersInitialized() { for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { if (project.isAccessible() && CeylonNature.isEnabled(project) && ! containersInitialized.contains(project)) { return false; } } return true; } public static ModuleDependencies getModuleDependenciesForProject( IProject project) { return projectModuleDependencies.get(project); } }
package com.redhat.ceylon.eclipse.core.model.loader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.lookup.FieldBinding; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding; import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding; import com.redhat.ceylon.compiler.loader.mirror.AnnotationMirror; import com.redhat.ceylon.compiler.loader.mirror.ClassMirror; import com.redhat.ceylon.compiler.loader.mirror.FieldMirror; import com.redhat.ceylon.compiler.loader.mirror.MethodMirror; import com.redhat.ceylon.compiler.loader.mirror.PackageMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeMirror; import com.redhat.ceylon.compiler.loader.mirror.TypeParameterMirror; public class JDTClass implements ClassMirror { private ReferenceBinding klass; private LookupEnvironment lookupEnvironment; private PackageMirror pkg; private TypeMirror superclass; private List<MethodMirror> methods; private List<TypeMirror> interfaces; private Map<String, AnnotationMirror> annotations; private List<TypeParameterMirror> typeParams; private List<FieldMirror> fields; private String qualifiedName; private String simpleName; private boolean superClassSet = false; private List<ClassMirror> innerClasses; public JDTClass(ReferenceBinding klass, LookupEnvironment lookupEnvironment) { this.klass = klass; this.lookupEnvironment = lookupEnvironment; } @Override public AnnotationMirror getAnnotation(String type) { if (annotations == null) { annotations = JDTUtils.getAnnotations(klass.getAnnotations()); } return annotations.get(type); } @Override public boolean isPublic() { if (klass != null) { return klass.isPublic(); } return true; } @Override public String getQualifiedName() { if (qualifiedName == null) { qualifiedName = JDTUtils.getFullyQualifiedName(klass); } return qualifiedName; } @Override public String getName() { if (simpleName == null) { simpleName = new String(klass.sourceName()); } return simpleName; } @Override public PackageMirror getPackage() { if (pkg == null) { pkg = new JDTPackage(klass.getPackage()); } return pkg; } @Override public boolean isInterface() { return klass.isInterface(); } @Override public boolean isAbstract() { return klass.isAbstract(); } @Override public List<MethodMirror> getDirectMethods() { if (methods == null) { MethodBinding[] directMethods; directMethods = klass.methods(); methods = new ArrayList<MethodMirror>(directMethods.length); for(MethodBinding method : directMethods) { methods.add(new JDTMethod(method, lookupEnvironment)); } } return methods; } @Override public TypeMirror getSuperclass() { if (! superClassSet) { if (klass.isInterface() || "java.lang.Object".equals(getQualifiedName())) { superclass = null; } else { ReferenceBinding superClassBinding = klass.superclass(); if (superClassBinding != null) { superClassBinding = JDTUtils.inferTypeParametersFromSuperClass(klass, superClassBinding, lookupEnvironment); superclass = new JDTType(superClassBinding); } } superClassSet = true; } return superclass; } @Override public List<TypeMirror> getInterfaces() { if (interfaces == null) { ReferenceBinding[] superInterfaces = klass.superInterfaces(); interfaces = new ArrayList<TypeMirror>(superInterfaces.length); for(ReferenceBinding superInterface : superInterfaces) interfaces.add(new JDTType(superInterface)); } return interfaces; } @Override public List<TypeParameterMirror> getTypeParameters() { if (typeParams == null) { TypeVariableBinding[] typeParameters = klass.typeVariables(); typeParams = new ArrayList<TypeParameterMirror>(typeParameters.length); for(TypeVariableBinding parameter : typeParameters) typeParams.add(new JDTTypeParameter(parameter)); } return typeParams; } private boolean isAnnotationPresent(Class<?> clazz) { return getAnnotation(clazz.getName()) != null; } @Override public boolean isCeylonToplevelAttribute() { return isAnnotationPresent(com.redhat.ceylon.compiler.java.metadata.Attribute.class); } @Override public boolean isCeylonToplevelObject() { return isAnnotationPresent(com.redhat.ceylon.compiler.java.metadata.Object.class); } @Override public boolean isCeylonToplevelMethod() { return isAnnotationPresent(com.redhat.ceylon.compiler.java.metadata.Method.class); } @Override public List<FieldMirror> getDirectFields() { if (fields == null) { FieldBinding[] directFields = klass.fields(); fields = new ArrayList<FieldMirror>(directFields.length); for(FieldBinding field : directFields) fields.add(new JDTField(field)); } return fields; } @Override public boolean isInnerClass() { return klass.isMemberType(); } @Override public ClassMirror getEnclosingClass() { //TODO: is this correct? ReferenceBinding enclosingType = klass.enclosingType(); return enclosingType==null ? null : new JDTClass(enclosingType, lookupEnvironment); } @Override public List<ClassMirror> getDirectInnerClasses() { if (innerClasses == null) { ReferenceBinding[] memberTypeBindings = klass.memberTypes(); innerClasses = new ArrayList<ClassMirror>(memberTypeBindings.length); for(ReferenceBinding memberTypeBinding : memberTypeBindings) { ReferenceBinding classBinding = (ReferenceBinding) memberTypeBinding; innerClasses.add(new JDTClass(classBinding, lookupEnvironment)); } } return innerClasses; } @Override public boolean isStatic() { return klass.isStatic(); } public String getFileName() { char[] fileName = klass.getFileName(); int start = CharOperation.lastIndexOf('/', fileName) + 1; if (start == 0 || start < CharOperation.lastIndexOf('\\', fileName)) start = CharOperation.lastIndexOf('\\', fileName) + 1; return new String(CharOperation.subarray(fileName, start, -1)); } public boolean isBinary() { return klass.isBinaryBinding(); } @Override public boolean isLoadedFromSource() { return false; } @Override public boolean isAnonymous() { return klass.isAnonymousType(); } @Override public boolean isJavaSource() { return (klass instanceof SourceTypeBinding) && new String(((SourceTypeBinding) klass).getFileName()).endsWith(".java"); } }
package org.jetbrains.idea.maven.dom.references; import com.intellij.codeInsight.lookup.*; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.lang.properties.psi.Property; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.ElementManipulators; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import com.intellij.psi.xml.XmlDocument; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTagChild; import com.intellij.util.Icons; import com.intellij.util.IncorrectOperationException; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.xml.XmlElementDescriptor; import com.intellij.xml.XmlNSDescriptor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.MavenSchemaProvider; import org.jetbrains.idea.maven.dom.model.*; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.utils.MavenIcons; import org.jetbrains.idea.maven.utils.MavenUtil; import org.jetbrains.idea.maven.vfs.MavenPropertiesVirtualFileSystem; import javax.swing.*; import java.util.ArrayList; import java.util.List; import java.util.Set; public class MavenPropertyPsiReference extends MavenPsiReference { protected final MavenDomProjectModel myProjectDom; protected final MavenProject myMavenProject; public MavenPropertyPsiReference(MavenProject mavenProject, PsiElement element, String text, TextRange range) { super(element, text, range); myMavenProject = mavenProject; myProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); } @Nullable public PsiElement resolve() { PsiElement result = doResolve(); if (result == null) return result; if (result instanceof XmlTag) { XmlTagChild[] children = ((XmlTag)result).getValue().getChildren(); if (children.length != 1 || !(children[0] instanceof Navigatable)) return result; return new MavenPsiElementWrapper(result, (Navigatable)children[0]); } return result; } // precedence // 1. user/system // 2. settings.xml // 3. profiles.xml // 4. profiles in pom.xml // 5. pom.xml // 6. parent profiles.xml // 7. profiles in parent pom.xml // 8. parent pom.xml // 9. model @Nullable protected PsiElement doResolve() { if (myText.startsWith("env.")) { return resolveEnvPropety(); } if (myText.equals("basedir") || myText.equals("project.basedir") || myText.equals("pom.basedir")) { return resolveBasedir(); } PsiElement result = resolveSystemPropety(); if (result != null) return result; result = processProperties(myProjectDom, new PropertyProcessor<PsiElement>() { @Nullable public PsiElement process(@NotNull XmlTag property) { if (property.getName().equals(myText)) return property; return null; } }); if (result != null) return result; if (myText.startsWith("settings.")) { return resolveSettingsModelProperty(); } String modelProperty = myText; if (!modelProperty.startsWith("project.")) { modelProperty = modelProperty.startsWith("pom.") ? "project." + modelProperty.substring("pom.".length()) : "project." + modelProperty; } return resolveModelProperty(myProjectDom, modelProperty, new THashSet<DomElement>()); } @Nullable private PsiElement resolveSystemPropety() { return MavenDomUtil.findProperty(myProject, MavenPropertiesVirtualFileSystem.SYSTEM_PROPERTIES_FILE, myText); } @Nullable private PsiElement resolveEnvPropety() { return MavenDomUtil.findProperty(myProject, MavenPropertiesVirtualFileSystem.ENV_PROPERTIES_FILE, myText.substring("env.".length())); } @Nullable private PsiElement resolveBasedir() { return getBaseDir(); } private PsiDirectory getBaseDir() { return PsiManager.getInstance(myProject).findDirectory(myMavenProject.getDirectoryFile()); } @Nullable private <T> T processProperties(@NotNull MavenDomProjectModel projectDom, final PropertyProcessor<T> processor) { T result; MavenProject mavenProject = MavenDomUtil.findProject(projectDom); result = processSettingsXmlProperties(mavenProject, processor); if (result != null) return result; result = processProjectProperties(myVirtualFile, projectDom, mavenProject, processor); if (result != null) return result; return new MyMavenParentProjectFileProcessor<T>() { protected T doProcessParent(VirtualFile parentFile) { MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, parentFile); MavenProject parentMavenProject = MavenDomUtil.findProject(parentProjectDom); return processProjectProperties(parentFile, parentProjectDom, parentMavenProject, processor); } }.process(projectDom); } @Nullable private <T> T processSettingsXmlProperties(@Nullable MavenProject mavenProject, PropertyProcessor<T> processor) { MavenGeneralSettings settings = myProjectsManager.getGeneralSettings(); T result; for (VirtualFile each : settings.getEffectiveSettingsFiles()) { MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(myProject, each, MavenDomSettingsModel.class); if (settingsDom == null) continue; result = processProfilesProperties(settingsDom.getProfiles(), mavenProject, processor); if (result != null) return result; } return null; } @Nullable private <T> T processProjectProperties(VirtualFile file, MavenDomProjectModel projectDom, MavenProject mavenProject, PropertyProcessor<T> processor) { T result; result = processProfilesXmlProperties(file, mavenProject, processor); if (result != null) return result; result = processProfilesProperties(projectDom.getProfiles(), mavenProject, processor); if (result != null) return result; return processProperties(projectDom.getProperties(), processor); } @Nullable private <T> T processProfilesXmlProperties(VirtualFile projectFile, MavenProject mavenProject, PropertyProcessor<T> processor) { VirtualFile profilesFile = MavenUtil.findProfilesXmlFile(projectFile); if (profilesFile == null) return null; MavenDomProfiles profiles = MavenDomUtil.getMavenDomProfilesModel(myProject, profilesFile); if (profiles == null) return null; return processProfilesProperties(profiles, mavenProject, processor); } @Nullable private <T> T processProfilesProperties(MavenDomProfiles profilesDom, MavenProject mavenProject, PropertyProcessor<T> processor) { List<String> activePropfiles = mavenProject == null ? null : mavenProject.getActiveProfilesIds(); for (MavenDomProfile each : profilesDom.getProfiles()) { XmlTag idTag = each.getId().getXmlTag(); if (idTag == null) continue; if (activePropfiles != null && !activePropfiles.contains(idTag.getValue().getText())) continue; T result = processProperties(each.getProperties(), processor); if (result != null) return result; } return null; } @Nullable private <T> T processProperties(MavenDomProperties propertiesDom, PropertyProcessor<T> processor) { XmlTag propertiesTag = propertiesDom.getXmlTag(); if (propertiesTag != null) { for (XmlTag each : propertiesTag.getSubTags()) { T result = processor.process(each); if (result != null) return result; } } return null; } @Nullable private PsiElement resolveSettingsModelProperty() { if (!schemaHasProperty(MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, myText)) return null; for (VirtualFile each : myProjectsManager.getGeneralSettings().getEffectiveSettingsFiles()) { MavenDomSettingsModel settingsDom = MavenDomUtil.getMavenDomModel(myProject, each, MavenDomSettingsModel.class); if (settingsDom == null) continue; PsiElement result = MavenDomUtil.findTag(settingsDom, myText); if (result != null) return result; } return myElement; } @Nullable private PsiElement resolveModelProperty(@NotNull MavenDomProjectModel projectDom, @NotNull final String path, @NotNull final Set<DomElement> recursionGuard) { if (recursionGuard.contains(projectDom)) return null; recursionGuard.add(projectDom); if (!schemaHasProperty(MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, path)) return null; PsiElement result = MavenDomUtil.findTag(projectDom, path); if (result != null) return result; if (path.equals("project.groupId") || path.equals("project.version")) { return MavenDomUtil.findTag(projectDom, path.replace("project.", "project.parent.")); } result = new MyMavenParentProjectFileProcessor<PsiElement>() { protected PsiElement doProcessParent(VirtualFile parentFile) { MavenDomProjectModel parentProjectDom = MavenDomUtil.getMavenDomProjectModel(myProject, parentFile); return resolveModelProperty(parentProjectDom, path, recursionGuard); } }.process(projectDom); if (result != null) return result; return myElement; } private boolean schemaHasProperty(String schema, final String property) { return processSchema(schema, new SchemaProcessor<Boolean>() { @Nullable public Boolean process(@NotNull String eachProperty, XmlElementDescriptor descriptor) { if (eachProperty.equals(property)) return true; return null; } }) != null; } @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { return ElementManipulators.getManipulator(myElement).handleContentChange(myElement, myRange, newElementName); } @NotNull public Object[] getVariants() { List<Object> result = new ArrayList<Object>(); collectVariants(result); return result.toArray(new Object[result.size()]); } protected void collectVariants(List<Object> result) { collectBasedirVariants(result); collectProjectSchemaVariants(result); collectSettingsXmlSchemaVariants(result); collectPropertiesVariants(result); collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.SYSTEM_PROPERTIES_FILE, null, result); collectSystemEnvProperties(MavenPropertiesVirtualFileSystem.ENV_PROPERTIES_FILE, "env.", result); } private void collectBasedirVariants(List<Object> result) { PsiDirectory basedir = getBaseDir(); result.add(createLookupElement(basedir, "basedir", MavenIcons.MAVEN_ICON)); result.add(createLookupElement(basedir, "pom.basedir", MavenIcons.MAVEN_ICON)); result.add(createLookupElement(basedir, "project.basedir", MavenIcons.MAVEN_ICON)); } private void collectProjectSchemaVariants(final List<Object> result) { processSchema(MavenSchemaProvider.MAVEN_PROJECT_SCHEMA_URL, new CollectingSchemaProcessor(result) { @Override public Object process(@NotNull String property, XmlElementDescriptor descriptor) { super.process(property, descriptor); String prefix = "project."; if (property.length() > prefix.length()) { String unqualified = property.substring(prefix.length()); super.process("pom." + unqualified, descriptor); super.process(unqualified, descriptor); } return null; } }); } private void collectSettingsXmlSchemaVariants(final List<Object> result) { processSchema(MavenSchemaProvider.MAVEN_SETTINGS_SCHEMA_URL, new CollectingSchemaProcessor(result)); } private void collectPropertiesVariants(final List<Object> result) { processProperties(myProjectDom, new PropertyProcessor<Object>() { public Object process(@NotNull XmlTag property) { result.add(createLookupElement(property, property.getName())); return null; } }); } private void collectSystemEnvProperties(String propertiesFileName, String prefix, List<Object> result) { PropertiesFile file = MavenDomUtil.getPropertiesFile(myProject, propertiesFileName); collectPropertiesFileVariants(file, prefix, result); } protected void collectPropertiesFileVariants(PropertiesFile file, String prefix, List<Object> result) { for (Property each : file.getProperties()) { String name = each.getKey(); if (prefix != null) name = prefix + name; result.add(createLookupElement(each, name)); } } private LookupElement createLookupElement(Object element, String name) { return createLookupElement(element, name, Icons.PROPERTY_ICON); } private LookupElement createLookupElement(Object element, String name, Icon icon) { return LookupElementFactory.builder(name, element).setIcon(icon).setPresentableText(name).createLookupElement(); } @Nullable private <T> T processSchema(String schema, SchemaProcessor<T> processor) { VirtualFile file = MavenSchemaProvider.getSchemaFile(schema); XmlFile xmlFile = (XmlFile)PsiManager.getInstance(myProject).findFile(file); XmlDocument document = xmlFile.getDocument(); XmlNSDescriptor desc = (XmlNSDescriptor)document.getMetaData(); XmlElementDescriptor[] descriptors = desc.getRootElementsDescriptors(document); return doProcessSchema(descriptors, null, processor, new THashSet<XmlElementDescriptor>()); } private <T> T doProcessSchema(XmlElementDescriptor[] descriptors, String prefix, SchemaProcessor<T> processor, Set<XmlElementDescriptor> recursionGuard) { for (XmlElementDescriptor each : descriptors) { if (isCollection(each)) continue; if (recursionGuard.contains(each)) continue; recursionGuard.add(each); try { String name = each.getName(); if (prefix != null) name = prefix + "." + name; T result = processor.process(name, each); if (result != null) return result; result = doProcessSchema(each.getElementsDescriptors(null), name, processor, recursionGuard); if (result != null) return result; } finally { recursionGuard.remove(each); } } return null; } private <T> boolean isCollection(XmlElementDescriptor each) { XmlTag declaration = (XmlTag)each.getDeclaration(); if (declaration != null) { XmlTag complexType = declaration.findFirstSubTag("xs:complexType"); if (complexType != null) { if (complexType.findFirstSubTag("xs:sequence") != null) return true; } } return false; } private interface PropertyProcessor<T> { @Nullable T process(@NotNull XmlTag property); } private interface SchemaProcessor<T> { @Nullable T process(@NotNull String property, XmlElementDescriptor descriptor); } private class CollectingSchemaProcessor implements SchemaProcessor { private final List<Object> myResult; public CollectingSchemaProcessor(List<Object> result) { myResult = result; } @Nullable public Object process(@NotNull String property, XmlElementDescriptor descriptor) { myResult.add(createLookupElement(descriptor, property, MavenIcons.MAVEN_ICON)); return null; } } private abstract class MyMavenParentProjectFileProcessor<T> extends MavenParentProjectFileProcessor<T> { protected VirtualFile findManagedFile(@NotNull MavenId id) { MavenProject project = myProjectsManager.findProject(id); return project == null ? null : project.getFile(); } @Nullable public T process(@NotNull MavenDomProjectModel projectDom) { MavenDomParent parent = projectDom.getMavenParent(); MavenParentDesc parentDesc = null; if (DomUtil.hasXml(parent)) { String parentGroupId = parent.getGroupId().getStringValue(); String parentArtifactId = parent.getArtifactId().getStringValue(); String parentVersion = parent.getVersion().getStringValue(); String parentRelativePath = parent.getRelativePath().getStringValue(); if (StringUtil.isEmptyOrSpaces(parentRelativePath)) parentRelativePath = "../pom.xml"; MavenId parentId = new MavenId(parentGroupId, parentArtifactId, parentVersion); parentDesc = new MavenParentDesc(parentId, parentRelativePath); } return process(myProjectsManager.getGeneralSettings(), myVirtualFile, parentDesc); } } }
package org.eclipse.thym.android.core.adt; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.IStreamListener; import org.eclipse.debug.core.model.IStreamMonitor; import org.eclipse.thym.android.core.AndroidConstants; import org.eclipse.thym.android.core.AndroidCore; import org.eclipse.thym.core.HybridMobileStatus; import org.eclipse.thym.core.HybridProjectConventions; import org.eclipse.thym.core.internal.util.ExternalProcessUtility; import org.eclipse.thym.core.internal.util.TextDetectingStreamListener; /** * Wrapper around the Android CommandLine tools. * * @author Gorkem Ercan * */ public class AndroidSDKManager { private String toolsDir; private String platformTools; private static class DeviceListParser implements IStreamListener{ private StringBuffer buffer = new StringBuffer(); @Override public void streamAppended(String text, IStreamMonitor monitor) { buffer.append(text); } public List<AndroidDevice> getDeviceList(){ if (buffer == null || buffer.length() < 1) return null; StringReader reader = new StringReader(buffer.toString()); BufferedReader read = new BufferedReader(reader); String line =null; ArrayList<AndroidDevice> list = new ArrayList<AndroidDevice>(); try{ while ((line = read.readLine()) != null) { if(line.isEmpty() || line.contains("List of devices attached")) continue; String[] values = line.split("\t"); if(values.length == 2){ AndroidDevice device = new AndroidDevice(); device.setSerialNumber(values[0].trim()); device.setEmulator(values[0].contains("emulator")); if("device".equals(values[1].trim())){ device.setState(AndroidDevice.STATE_DEVICE); } else if("offline".equals(values[1].trim())){ device.setState(AndroidDevice.STATE_OFFLINE); } list.add(device); } } } catch (IOException e) { AndroidCore.log(IStatus.ERROR, "Error parsing the Android device list", e); return null; } finally{ try{ read.close(); reader.close(); }catch(IOException e){/*ignored*/} } return list; } } private static class AVDListParser implements IStreamListener{ private static final String PREFIX_NAME = "Name:"; private static final String MARKER_LEVEL = "API level"; private StringBuffer buffer = new StringBuffer(); @Override public void streamAppended(String text, IStreamMonitor monitor) { buffer.append(text); } public List<AndroidAVD> getAVDList(){ if (buffer == null || buffer.length() < 1) return null; StringReader reader = new StringReader(buffer.toString()); BufferedReader read = new BufferedReader(reader); String line =null; ArrayList<AndroidAVD> list = new ArrayList<AndroidAVD>(); try{ AndroidAVD currentAVD = null; while ((line = read.readLine()) != null) { int idx = line.indexOf(PREFIX_NAME); if(idx > -1){ currentAVD = new AndroidAVD(); currentAVD.setName(line.substring(idx+PREFIX_NAME.length()).trim()); continue; } idx = line.indexOf(MARKER_LEVEL) ; if(idx > -1 && currentAVD != null){ int startIndex = idx + MARKER_LEVEL.length(); int endIndex = line.lastIndexOf(')'); currentAVD.setApiLevel((line.substring(startIndex, endIndex).trim())); list.add(currentAVD); currentAVD = null; } } } catch (IOException e) { AndroidCore.log(IStatus.ERROR, "Error parsing the AVD list", e); return Collections.emptyList(); } finally{ try{ read.close(); reader.close(); }catch(IOException e){/*ignored*/} } return list; } } private static class TargetListParser implements IStreamListener{ private StringBuffer buffer = new StringBuffer(); @Override public void streamAppended(String text, IStreamMonitor monitor) { buffer.append(text); } public List<AndroidSDK> getSDKList() { if (buffer == null || buffer.length() < 1) return null; StringReader reader = new StringReader(buffer.toString()); BufferedReader read = new BufferedReader(reader); ArrayList<AndroidSDK> sdkList = new ArrayList<AndroidSDK>(); String line = null; try { AndroidSDK sdk = null; while ((line = read.readLine()) != null) { final int scolIdx = line.indexOf(':'); if (scolIdx < 0) { continue; } String[] pair = new String[2]; pair[0] = line.substring(0, scolIdx).trim(); pair[1] = line.substring(scolIdx + 1).trim(); if ("id".equalsIgnoreCase(pair[0])) { sdk = new AndroidSDK(); sdkList.add(sdk); int vIndex = pair[1].indexOf("or"); sdk.setId(pair[1].substring(vIndex + "or".length()) .replace("\"", "").trim()); } else if ("Type".equalsIgnoreCase(pair[0])) { Assert.isNotNull(sdk); sdk.setType(pair[1].trim()); } else if ("API level".equalsIgnoreCase(pair[0])) { Assert.isNotNull(sdk); sdk.setApiLevel(pair[1]); } } } catch (IOException e) { AndroidCore.log(IStatus.ERROR, "Error parsing the SDK list", e); } finally{ try{ read.close(); reader.close(); }catch(IOException e){ //ignored } } return sdkList; } } private static class CreateProjectResultParser implements IStreamListener{ private StringBuffer buffer = new StringBuffer(); @Override public void streamAppended(String text, IStreamMonitor monitor) { buffer.append(text); } /** * Returns an error string or null if it is OK * @return */ public String getErrorString(){ String text = buffer.toString(); if (text.startsWith("Error:")) { StringReader reader = new StringReader(text); BufferedReader read = new BufferedReader(reader); try { String line = read.readLine(); if(line==null){ return ""; } return line.substring(7); } catch (IOException e) { AndroidCore.log(IStatus.ERROR, "Error parsing the create project command result", e); } finally{ try{ read.close(); reader.close(); }catch(IOException e){ //ignored } } } return null; } } private AndroidSDKManager(String tools, String platform) { toolsDir = tools; platformTools = platform; } public static AndroidSDKManager getManager() throws CoreException{ String sdkDir = AndroidCore.getSDKLocation(); if(sdkDir == null ){ throw new CoreException(new HybridMobileStatus(IStatus.ERROR, AndroidCore.PLUGIN_ID, AndroidConstants.STATUS_CODE_ANDROID_SDK_NOT_DEFINED, "Android SDK location is not defined", null)); } Path path = new Path(sdkDir); IPath tools = path.append("tools").addTrailingSeparator(); IPath platform = path.append("platform-tools").addTrailingSeparator(); AndroidSDKManager sdk = new AndroidSDKManager(tools.toOSString(), platform.toOSString()); return sdk; } public void createProject(AndroidSDK target, String projectName, File path, String activity, String packageName, IProgressMonitor monitor) throws CoreException{ IStatus status = HybridProjectConventions.validateProjectName(projectName); if(!status.isOK()) throw new CoreException(status); //activity class name matches the project name status = HybridProjectConventions.validateProjectName(activity); if(!status.isOK()) throw new CoreException(status); status = HybridProjectConventions.validateProjectID(packageName); if(!status.isOK()) throw new CoreException(status); ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(); command.append(getAndroidCommand()); command.append(" create project"); command.append(" --target ").append(target.getId()); command.append(" --path ").append(addQuotes(path.getPath())); command.append(" --name ").append(addQuotes(projectName)); command.append(" --activity ").append(activity); command.append(" --package ").append(packageName); CreateProjectResultParser parser = new CreateProjectResultParser(); processUtility.execSync(command.toString(), new File(toolsDir), parser, parser, monitor, null, null); if( !monitor.isCanceled() && parser.getErrorString() != null ){ throw new CoreException(new Status(IStatus.ERROR,AndroidCore.PLUGIN_ID,"Error creating the Android project: "+ parser.getErrorString())); } } public void updateProject(AndroidSDK sdk, String projectName, boolean isLibrary,File path, IProgressMonitor monitor)throws CoreException{ StringBuilder command = new StringBuilder(getAndroidCommand()); command.append(" update"); if(isLibrary){ command.append(" lib-project"); }else{ command.append(" project"); } command.append( " --target ").append(sdk.getId()); if(projectName != null ){ IStatus status = HybridProjectConventions.validateProjectName(projectName); if(!status.isOK()){ throw new CoreException(status); } command.append(" --name ").append('"').append(projectName).append('"'); } command.append(" --path ").append('"').append(path.getPath()).append('"'); ExternalProcessUtility processUtility = new ExternalProcessUtility(); CreateProjectResultParser parser = new CreateProjectResultParser(); processUtility.execSync(command.toString(), new File(toolsDir), parser, parser, monitor, null, null); if( !monitor.isCanceled() && parser.getErrorString() != null ){ throw new CoreException(new Status(IStatus.ERROR,AndroidCore.PLUGIN_ID,"Error creating the Android project: "+ parser.getErrorString())); } } public void startADBServer() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); processUtility.execSync(getADBCommand()+" start-server",null, null, null, new NullProgressMonitor(), null, null); } public void killADBServer() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); processUtility.execSync(getADBCommand()+" kill-server",null, null, null, new NullProgressMonitor(), null, null); } public List<AndroidAVD> listAVDs() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); AVDListParser parser = new AVDListParser(); processUtility.execSync(getAndroidCommand()+" list avd", new File(toolsDir), parser, parser, new NullProgressMonitor(), null, null); return parser.getAVDList(); } public List<AndroidSDK> listTargets() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); TargetListParser parser = new TargetListParser(); processUtility.execSync(getAndroidCommand()+" list target", new File(toolsDir), parser, parser, new NullProgressMonitor(), null, null); return parser.getSDKList(); } public List<AndroidDevice> listDevices() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); DeviceListParser parser = new DeviceListParser(); processUtility.execSync(getADBCommand()+" devices", null, parser, parser, new NullProgressMonitor(), null, null); List<AndroidDevice> devices = parser.getDeviceList(); if(devices == null ){ devices = Collections.emptyList(); } return devices; } public void installApk(File apkFile, String serialNumber, IProgressMonitor monitor) throws CoreException{ Assert.isNotNull(serialNumber); ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(getADBCommand()); command.append(" -s ").append(serialNumber); command.append(" install"); command.append(" -r "); command.append("\"").append(apkFile.getPath()).append("\""); TextDetectingStreamListener listener = new TextDetectingStreamListener("Success"); processUtility.execSync(command.toString(), null,listener, listener, monitor, null, null); if (!monitor.isCanceled() && !listener.isTextDetected()){ throw new CoreException(new Status(IStatus.ERROR, AndroidCore.PLUGIN_ID, "APK installation did not succeed")); } } public void waitForEmulator() throws CoreException{ while(true){ List<AndroidDevice> devices = this.listDevices(); if(devices != null ){ for (AndroidDevice androidDevice : devices) { if(androidDevice.isEmulator() && androidDevice.getState() == AndroidDevice.STATE_DEVICE) return; } } try { Thread.sleep(200); } catch (InterruptedException e) { } } } public void startApp(String component, String serialNumber, IProgressMonitor monitor) throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(getADBCommand()); command.append(" -s ").append(serialNumber); command.append(" shell am start"); command.append(" -n "); command.append(component); processUtility.execSync(command.toString(), null, null, null, monitor, null, null); } public void logcat(String filter, IStreamListener outListener, IStreamListener errorListener, String serialNumber) throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(getADBCommand()); command.append(" -s ").append(serialNumber); command.append(" logcat "); if(filter !=null && !filter.isEmpty()){ command.append(filter); } processUtility.execAsync(command.toString(), null, outListener, errorListener, null); } public void startEmulator(String avd) throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(getEmulatorCommand()); command.append(" -cpu-delay 0"); command.append(" -no-boot-anim"); command.append(" -avd ").append(avd); processUtility.execAsync(command.toString(), null, null, null, null); } public void startAVDManager() throws CoreException{ ExternalProcessUtility processUtility = new ExternalProcessUtility(); StringBuilder command = new StringBuilder(getAndroidCommand()); command.append(" avd "); processUtility.execAsync(command.toString(), new File(toolsDir), null, null, null); } private String getAndroidCommand(){ String scriptName = isWindows() ? "android.bat" : "android"; return addQuotes(toolsDir + scriptName); } private String getADBCommand(){ return addQuotes(platformTools+"adb"); } private String getEmulatorCommand(){ return addQuotes(toolsDir+"emulator"); } private boolean isWindows(){ String OS = System.getProperty("os.name","unknown"); return OS.toLowerCase().indexOf("win")>-1; } private String addQuotes(String path) { return "\"" + path + "\""; } }
package com.intellij.structuralsearch.duplicates; import com.intellij.lang.Language; import com.intellij.lang.xml.XMLLanguage; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlTokenType; import org.jetbrains.annotations.NotNull; /** * @author Eugene.Kudelevsky */ public class XmlDuplicatesProfile extends SSRDuplicatesProfileBase { private static final TokenSet LITERALS = TokenSet.create(XmlTokenType.XML_DATA_CHARACTERS, XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN); @Override public boolean isMyLanguage(@NotNull Language language) { return language instanceof XMLLanguage; } @Override public int getNodeCost(@NotNull PsiElement element) { if (element instanceof XmlTag) { return 3; } else if (element instanceof XmlAttribute) { return 1; } return 0; } @Override public TokenSet getLiterals() { return LITERALS; } }
package org.xcolab.portlets.contactform; import java.io.IOException; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.portlet.PortletPreferences; import javax.portlet.ReadOnlyException; import javax.portlet.ValidatorException; import com.liferay.portal.model.User; public class ContactPreferences { private String receipients; private String messageFormat; private String messageSubject; private String expandLinkText; private final static String RECEIPIENTS_PREF = "RECEIPIENTS"; private final static String MESSAGE_FORMAT_PREF = "MESSAGE_FORMAT"; private final static String MESSAGE_SUBJECT_PREF = "MESSAGE_SUBJECT"; private final static String EXPAND_LINK_TEXT_PREF = "EXPAND_LINK_TEXT"; private final static String defaultReceipients = "rjl@mit.edu,janusz.parfieniuk@gmail.com,jintrone@MIT.EDU,pdeboer@mit.edu"; private final static String defaultMessageFormat = "USER_NAME (USER_EMAIL) has sent message using contact form\nUSER_MESSAGE"; private final static String defaultMessageSubject = "[CoLab] USER_NAME sent a message using contact form"; private final static String defaultExpandLinkText = "Send feedback message"; public List<User> getMessageRecipients() { // TODO Auto-generated method stub return null; } public ContactPreferences() { PortletPreferences prefs = Helper.getPortletPrefs(); messageFormat = prefs.getValue(MESSAGE_FORMAT_PREF, defaultMessageFormat); messageSubject = prefs.getValue(MESSAGE_SUBJECT_PREF, defaultMessageSubject); expandLinkText = prefs.getValue(EXPAND_LINK_TEXT_PREF, defaultExpandLinkText); receipients = prefs.getValue(RECEIPIENTS_PREF, defaultReceipients); } public String getReceipients() { return receipients; } public String[] getReceipientsArray() { return receipients.split(","); } public void setReceipients(String receipients) { this.receipients = receipients; } public String getMessageFormat() { return messageFormat; } public void setMessageFormat(String messageFormat) { this.messageFormat = messageFormat; } public String getMessageSubject() { return messageSubject; } public void setMessageSubject(String messageSubject) { this.messageSubject = messageSubject; } public String getExpandLinkText() { return expandLinkText; } public void setExpandLinkText(String expandLinkText) { this.expandLinkText = expandLinkText; } public static String getReceipientsPref() { return RECEIPIENTS_PREF; } public static String getMessageFormatPref() { return MESSAGE_FORMAT_PREF; } public static String getMessageSubjectPref() { return MESSAGE_SUBJECT_PREF; } public String submit() throws ReadOnlyException, ValidatorException, IOException { PortletPreferences prefs = Helper.getPortletPrefs(); prefs.setValue(MESSAGE_FORMAT_PREF, messageFormat); prefs.setValue(MESSAGE_SUBJECT_PREF, messageSubject); prefs.setValue(EXPAND_LINK_TEXT_PREF, expandLinkText); prefs.setValue(RECEIPIENTS_PREF, receipients); prefs.store(); FacesMessage fm = new FacesMessage(); fm.setSummary("Settings saved successfully"); fm.setSeverity(FacesMessage.SEVERITY_INFO); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(null, fm); return null; } }
package com.opengamma.integration.tool.marketdata; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.threeten.bp.Instant; import org.threeten.bp.ZonedDateTime; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.id.ObjectId; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotDocument; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotHistoryRequest; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotHistoryResult; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotSearchRequest; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotSearchResult; /** * Utility class to provide services to snapshot command line tools (and potentially UI tools too). */ public final class SnapshotUtils { private static final Logger s_logger = LoggerFactory.getLogger(SnapshotUtils.class); private MarketDataSnapshotMaster _snapshotMaster; private SnapshotUtils(MarketDataSnapshotMaster snapshotMaster) { _snapshotMaster = snapshotMaster; } public static SnapshotUtils of(MarketDataSnapshotMaster snapshotMaster) { return new SnapshotUtils(snapshotMaster); } /** * Get a list of all available snapshot names * @return the list of all available snapshot ids and names or an empty list if no snapshots found */ public List<String> allSnapshots() { MarketDataSnapshotSearchRequest searchRequest = new MarketDataSnapshotSearchRequest(); searchRequest.setIncludeData(false); MarketDataSnapshotSearchResult searchResult = _snapshotMaster.search(searchRequest); List<String> results = new ArrayList<>(); for (MarketDataSnapshotDocument doc : searchResult.getDocuments()) { results.add(doc.getUniqueId() + " - " + doc.getName()); } return results; } /** * Get a list of snapshot names according to a glob query string * @param query the query string, which can contain wildcards * @return the list of resulting snapshot names or an empty list if no matches */ public List<String> snapshotNamesByGlob(String query) { MarketDataSnapshotSearchRequest searchRequest = new MarketDataSnapshotSearchRequest(); searchRequest.setName(query); MarketDataSnapshotSearchResult searchResult = _snapshotMaster.search(searchRequest); List<String> results = new ArrayList<>(); for (MarketDataSnapshotDocument doc : searchResult.getDocuments()) { results.add(doc.getName()); } return results; } /** * Get the latest snapshot by name * @param name exact name of the snapshot, not null * @return the UniqueId of the matched snapshot, or null if no match found * @throws OpenGammaRuntimeException if multiple matches are found */ public UniqueId latestSnapshotByName(String name) { MarketDataSnapshotSearchRequest searchRequest = new MarketDataSnapshotSearchRequest(); searchRequest.setName(name); searchRequest.setIncludeData(false); MarketDataSnapshotSearchResult searchResult = _snapshotMaster.search(searchRequest); if (searchResult.getDocuments().size() > 1) { throw new OpenGammaRuntimeException("More than one snapshot matches supplied name"); } if (searchResult.getDocuments().size() == 0) { return null; } return searchResult.getFirstDocument().getUniqueId(); } /** * Get the latest snapshot by name * @param name exact name of the snapshot, not null * @param dateTime the date/time of the version of the snapshot to fetch * @return the UniqueId of the matched snapshot, or null if no match found * @throws OpenGammaRuntimeException if multiple matches are found */ public UniqueId latestSnapshotByNameAndDate(String name, ZonedDateTime dateTime) { MarketDataSnapshotSearchRequest searchRequest = new MarketDataSnapshotSearchRequest(); searchRequest.setName(name); searchRequest.setIncludeData(false); MarketDataSnapshotSearchResult searchResult = _snapshotMaster.search(searchRequest); searchRequest.setVersionCorrection(VersionCorrection.ofVersionAsOf(dateTime.toInstant())); if (searchResult.getDocuments().size() > 1) { throw new OpenGammaRuntimeException("More than one snapshot matches supplied name"); } if (searchResult.getDocuments().size() == 0) { return null; } return searchResult.getFirstDocument().getUniqueId(); } /** * Get meta data about available versions of a snapshot by it's name * @param name exact name of the snapshot, not null * @return a list of VersionInfo meta data objects containing version correction ranges and unique ids * @throws OpenGammaRuntimeException if multiple name matches are found */ public List<VersionInfo> snapshotVersionsByName(String name) { MarketDataSnapshotSearchRequest searchRequest = new MarketDataSnapshotSearchRequest(); searchRequest.setName(name); searchRequest.setIncludeData(false); MarketDataSnapshotSearchResult searchResult = _snapshotMaster.search(searchRequest); if (searchResult.getDocuments().size() > 1) { s_logger.warn("More than one snapshot matches supplied name, using first"); } if (searchResult.getDocuments().size() == 0) { return Collections.emptyList(); } ObjectId objectId = searchResult.getFirstDocument().getObjectId(); MarketDataSnapshotHistoryResult historyResult = _snapshotMaster.history(new MarketDataSnapshotHistoryRequest(objectId)); List<VersionInfo> results = new ArrayList<>(); for (MarketDataSnapshotDocument doc : historyResult.getDocuments()) { results.add(new VersionInfo(doc.getVersionFromInstant(), doc.getCorrectionFromInstant(), doc.getVersionToInstant(), doc.getCorrectionToInstant(), doc.getUniqueId())); } return results; } /** * Class representing the version range information for a snapshot, including the UniqueId. */ public class VersionInfo { private Instant _versionFrom; private Instant _versionTo; private Instant _correctionFrom; private Instant _correctionTo; private UniqueId _uniqueId; public VersionInfo(Instant versionFrom, Instant versionTo, Instant correctionFrom, Instant correctionTo, UniqueId uniqueId) { _versionFrom = versionFrom; _versionTo = versionTo; _correctionFrom = correctionFrom; _correctionTo = correctionTo; _uniqueId = uniqueId; } public Instant getVersionFrom() { return _versionFrom; } public Instant getVersionTo() { return _versionTo; } public Instant getCorrectionFrom() { return _correctionFrom; } public Instant getCorrectionTo() { return _correctionTo; } public UniqueId getUniqueId() { return _uniqueId; } } }
package com.opengamma.language.identifier; import com.opengamma.language.convert.AbstractMappedConverter; import com.opengamma.language.convert.TypeMap; import com.opengamma.language.definition.JavaTypeInfo; /** * Converts ExternalSchemeRank to/from an array of strings. */ public class ExternalSchemeRankConverter extends AbstractMappedConverter { private static final JavaTypeInfo<String[]> STRING_ARRAY = JavaTypeInfo.builder(String[].class).allowNull().get(); private static final JavaTypeInfo<ExternalSchemeRank> EXTERNAL_SCHEME_RANK = JavaTypeInfo.builder(ExternalSchemeRank.class).allowNull().get(); /** * Default instance. */ public static final ExternalSchemeRankConverter INSTANCE = new ExternalSchemeRankConverter(); protected ExternalSchemeRankConverter() { conversion(TypeMap.ZERO_LOSS, STRING_ARRAY, EXTERNAL_SCHEME_RANK, new Action<String[], ExternalSchemeRank>() { @Override protected ExternalSchemeRank convert(final String[] value) { return ExternalSchemeRank.ofStrings(value); } }); conversion(TypeMap.MINOR_LOSS, EXTERNAL_SCHEME_RANK, STRING_ARRAY, new Action<ExternalSchemeRank, String[]>() { @Override protected String[] convert(final ExternalSchemeRank value) { return value.asStrings(); } }); } }
package com.jetbrains.python.codeInsight.intentions; import com.intellij.codeInsight.intention.impl.BaseIntentionAction; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.types.PyClassType; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.jetbrains.python.psi.PyUtil.sure; public class ConvertFormatOperatorToMethodIntention extends BaseIntentionAction { private static final Pattern FORMAT_PATTERN = Pattern.compile("%(?:\\((\\w+)\\))?([#0+ ]|-)?((?:\\*|\\d+)?(?:\\.(?:\\*|\\d+))?)?[hlL]?([diouxXeEfFgGcrs%])"); private static final Pattern BRACE_PATTERN = Pattern.compile("(\\{|\\})"); /** * copy source to target, doubling every brace. */ private static void appendDoublingBraces(CharSequence source, StringBuilder target) { int index = 0; Matcher scanner = BRACE_PATTERN.matcher(source); while (scanner.find(index)) { target.append(source.subSequence(index, scanner.start())); if ("{".equals(scanner.group(0))) target.append("{{"); else target.append("}}"); index = scanner.end(); } target.append(source.subSequence(index, source.length())); } /** * Converts format expressions inside a string * @param stringLiteralExpression * @return a pair of string builder with resulting string expression and a flag which is true if formats inside use mapping by name. */ private static Pair<StringBuilder, Boolean> convertFormat(PyStringLiteralExpression stringLiteralExpression) { // python string may be made of several literals, all different List<StringBuilder> constants = new ArrayList<StringBuilder>(); boolean uses_named_format = false; final List<ASTNode> text_nodes = stringLiteralExpression.getStringNodes(); sure(text_nodes); sure(text_nodes.size() > 0); for (ASTNode text_node : text_nodes) { // preserve prefixes and quote form CharSequence text = text_node.getChars(); int open_pos = 0; if ("uUbB".indexOf(text.charAt(open_pos)) >= 0) open_pos += 1; // unicode modifier if ("rR".indexOf(text.charAt(open_pos)) >= 0) open_pos += 1; // raw modifier char quote = text.charAt(open_pos); sure("\"'".indexOf(quote) >= 0); if (text.length() - open_pos >= 6) { // triple-quoted? if (text.charAt(open_pos+1) == quote && text.charAt(open_pos+2) == quote) { open_pos += 2; } } int index = open_pos + 1; // from quote to first in-string char StringBuilder out = new StringBuilder(text.subSequence(0, open_pos+1)); int position_count = 0; Matcher scanner = FORMAT_PATTERN.matcher(text); while (scanner.find(index)) { // store previous non-format part appendDoublingBraces(text.subSequence(index, scanner.start()), out); //out.append(text.subSequence(index, scanner.start())); // unpack format final String f_key = scanner.group(1); final String f_modifier = scanner.group(2); final String f_width = scanner.group(3); String f_conversion = scanner.group(4); // convert to format()'s if ("%%".equals(scanner.group(0))) { // shortcut to put a literal % out.append("%"); } else { sure(f_conversion); sure(!"%".equals(f_conversion)); // a padded percent literal; can't bother to autoconvert, and in 3k % is different. out.append("{"); if (f_key != null) { out.append(f_key); uses_named_format = true; } else { out.append(position_count); position_count += 1; } if ("r".equals(f_conversion)) out.append("!r"); // don't convert %s -> !s, for %s is the normal way to output the default representation out.append(":"); if (f_modifier != null) out.append(f_modifier); if (f_width != null) out.append(f_width); if ("i".equals(f_conversion) || "u".equals(f_conversion)) out.append("d"); else if ("r".equals(f_conversion)) out.append("s"); // we want our raw string as a string else out.append(f_conversion); out.append("}"); } index = scanner.end(); } // store non-format final part //out.append(text.subSequence(index, text.length()-1)); appendDoublingBraces(text.subSequence(index, text.length()), out); constants.add(out); } // form the entire literal filling possible gaps between constants. // we assume that a string literal begins with its first constant, without a gap. TextRange full_range = stringLiteralExpression.getTextRange(); int full_start = full_range.getStartOffset(); CharSequence full_text = stringLiteralExpression.getNode().getChars(); TextRange prev_range = text_nodes.get(0).getTextRange(); int fragment_no = 1; // look at second and further fragments while (fragment_no < text_nodes.size()) { TextRange next_range = text_nodes.get(fragment_no).getTextRange(); int left = prev_range.getEndOffset() - full_start; int right = next_range.getStartOffset() - full_start; if (left < right) { constants.get(fragment_no-1).append(full_text.subSequence(left, right)); } fragment_no += 1; prev_range = next_range; } final int left = prev_range.getEndOffset() - full_start; final int right = full_range.getEndOffset() - full_start; if (left < right) { // the barely possible case of last dangling "\" constants.get(constants.size()-1).append(full_text.subSequence(left, right)); } // join everything StringBuilder result = new StringBuilder(); for (StringBuilder one : constants) result.append(one); return new Pair<StringBuilder, Boolean>(result, uses_named_format); } @NotNull public String getFamilyName() { return PyBundle.message("INTN.format.operator.to.method"); } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { PyBinaryExpression binaryExpression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyBinaryExpression.class, false); if (binaryExpression == null) { return false; } final VirtualFile virtualFile = binaryExpression.getContainingFile().getVirtualFile(); if (virtualFile == null) { return false; } final LanguageLevel languageLevel = LanguageLevel.forFile(virtualFile); if (languageLevel.isOlderThan(LanguageLevel.PYTHON26)) { return false; } if (binaryExpression.getLeftExpression() instanceof PyStringLiteralExpression && binaryExpression.getOperator() == PyTokenTypes.PERC) { setText(PyBundle.message("INTN.replace.with.method")); return true; } return false; } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PyBinaryExpression element = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyBinaryExpression.class, false); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); final PyExpression rightExpression = sure(element).getRightExpression(); if (rightExpression == null) { return; } PyExpression rhs = rightExpression; while (rhs instanceof PyParenthesizedExpression) rhs = ((PyParenthesizedExpression)rhs).getContainedExpression(); String param_text = sure(rhs).getText(); final PyStringLiteralExpression leftExpression = (PyStringLiteralExpression)element.getLeftExpression(); Pair<StringBuilder, Boolean> converted = convertFormat(leftExpression); StringBuilder target = converted.getFirst(); String separator = ""; // detect nontrivial whitespace around the "%" Pair<String, PsiElement> crop = collectWhitespace(leftExpression); String maybe_separator = crop.getFirst(); if (!"".equals(maybe_separator) && !" ".equals(maybe_separator)) separator = maybe_separator; else { // after "%" crop = collectWhitespace(crop.getSecond()); maybe_separator = crop.getFirst(); if (!"".equals(maybe_separator) && !" ".equals(maybe_separator)) separator = maybe_separator; } target.append(separator).append(".format"); if (rhs instanceof PyDictLiteralExpression) target.append("(**").append(param_text).append(")"); else if (rhs instanceof PyCallExpression) { // potential dict(foo=1) -> format(foo=1) final PyCallExpression call_expression = (PyCallExpression)rhs; final PyExpression callee = call_expression.getCallee(); if (callee instanceof PyReferenceExpression) { PsiElement maybe_dict = ((PyReferenceExpression)callee).getReference().resolve(); if (maybe_dict instanceof PyFunction) { PyFunction dict_init = (PyFunction)maybe_dict; if (PyNames.INIT.equals(dict_init.getName())) { final PyClassType dict_type = PyBuiltinCache.getInstance(file).getDictType(); if (dict_type != null && dict_type.getPyClass() == dict_init.getContainingClass()) { target.append(sure(sure(call_expression.getArgumentList()).getNode()).getChars()); } } else { // just a call, reuse target.append("("); if (converted.getSecond()) target.append("**"); // map-by-name formatting was detected target.append(param_text).append(")"); } } } } else target.append("(").append(param_text).append(")"); // tuple is ok as is element.replace(elementGenerator.createExpressionFromText(target.toString())); } private static Pair<String, PsiElement> collectWhitespace(PsiElement start) { StringBuilder sb = new StringBuilder(); PsiElement seeker = start; while (seeker != null) { seeker = seeker.getNextSibling(); if (seeker != null && seeker instanceof PsiWhiteSpace) sb.append(seeker.getText()); else break; } return new Pair<String, PsiElement>(sb.toString(), seeker); } }
package fr.inria.spirals.repairnator.pipeline; import ch.qos.logback.classic.Level; import com.martiansoftware.jsap.*; import com.martiansoftware.jsap.stringparsers.EnumeratedStringParser; import com.martiansoftware.jsap.stringparsers.FileStringParser; import fr.inria.spirals.jtravis.entities.Build; import fr.inria.spirals.jtravis.entities.BuildStatus; import fr.inria.spirals.jtravis.helpers.BuildHelper; import fr.inria.spirals.repairnator.BuildToBeInspected; import fr.inria.spirals.repairnator.serializer.MetricsSerializer; import fr.inria.spirals.repairnator.states.LauncherMode; import fr.inria.spirals.repairnator.states.ScannedBuildStatus; import fr.inria.spirals.repairnator.Utils; import fr.inria.spirals.repairnator.config.RepairnatorConfig; import fr.inria.spirals.repairnator.notifier.AbstractNotifier; import fr.inria.spirals.repairnator.notifier.FixerBuildNotifier; import fr.inria.spirals.repairnator.notifier.PatchNotifier; import fr.inria.spirals.repairnator.notifier.engines.EmailNotifierEngine; import fr.inria.spirals.repairnator.notifier.engines.NotifierEngine; import fr.inria.spirals.repairnator.process.inspectors.ProjectInspector; import fr.inria.spirals.repairnator.process.inspectors.ProjectInspector4Bears; import fr.inria.spirals.repairnator.serializer.AbstractDataSerializer; import fr.inria.spirals.repairnator.serializer.HardwareInfoSerializer; import fr.inria.spirals.repairnator.serializer.InspectorSerializer; import fr.inria.spirals.repairnator.serializer.InspectorSerializer4Bears; import fr.inria.spirals.repairnator.serializer.InspectorTimeSerializer; import fr.inria.spirals.repairnator.serializer.InspectorTimeSerializer4Bears; import fr.inria.spirals.repairnator.serializer.NopolSerializer; import fr.inria.spirals.repairnator.serializer.engines.SerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.json.JSONFileSerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.json.MongoDBSerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.table.CSVSerializerEngine; import fr.inria.spirals.repairnator.serializer.engines.table.GoogleSpreadsheetSerializerEngine; import fr.inria.spirals.repairnator.serializer.gspreadsheet.GoogleSpreadSheetFactory; import fr.inria.spirals.repairnator.serializer.mongodb.MongoConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URLClassLoader; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; public class Launcher { private static Logger LOGGER = LoggerFactory.getLogger(Launcher.class); private JSAP jsap; private JSAPResult arguments; private RepairnatorConfig config; private int buildId; private BuildToBeInspected buildToBeInspected; private List<SerializerEngine> engines; public Launcher(String[] args) throws JSAPException { this.defineArgs(); this.arguments = jsap.parse(args); this.checkArguments(); this.initConfig(); if (this.config.getLauncherMode() == LauncherMode.REPAIR) { this.checkToolsLoaded(); this.checkNopolSolverPath(); } if (this.arguments.getBoolean("debug")) { Utils.setLoggersLevel(Level.DEBUG); } else { Utils.setLoggersLevel(Level.INFO); } this.buildId = this.arguments.getInt("build"); this.initializeSerializerEngines(); } private void initConfig() { this.config = RepairnatorConfig.getInstance(); this.config.setRunId(this.arguments.getString("runId")); this.config.setLauncherMode(LauncherMode.valueOf(this.arguments.getString("launcherMode").toUpperCase())); this.config.setClean(true); this.config.setZ3solverPath(this.arguments.getFile("z3").getPath()); if (this.arguments.getFile("outputPath") != null) { this.config.setSerializeJson(true); this.config.setJsonOutputPath(this.arguments.getFile("outputPath").getPath()); } if (this.arguments.getString("pushUrl") != null) { this.config.setPush(true); this.config.setPushRemoteRepo(this.arguments.getString("pushUrl")); } this.config.setWorkspacePath(this.arguments.getString("workspace")); this.config.setGithubLogin(this.arguments.getString("ghLogin")); this.config.setGithubToken(this.arguments.getString("ghOauth")); } private void initializeSerializerEngines() { this.engines = new ArrayList<>(); if (this.arguments.getString("spreadsheet") != null && this.arguments.getString("googleAccessToken") != null) { LOGGER.info("Initialize Google spreadsheet serializer engine."); GoogleSpreadSheetFactory.setSpreadsheetId(this.arguments.getString("spreadsheet")); try { if (GoogleSpreadSheetFactory.initWithAccessToken(this.arguments.getString("googleAccessToken"))) { this.engines.add(new GoogleSpreadsheetSerializerEngine()); } else { LOGGER.error("Error while initializing Google Spreadsheet, no information will be serialized in spreadsheets"); } } catch (IOException | GeneralSecurityException e) { LOGGER.error("Error while initializing Google Spreadsheet, no information will be serialized in spreadsheets", e); } } else { LOGGER.info("Google Spreadsheet won't be used for serialization."); } if (config.isSerializeJson()) { LOGGER.info("Initialize files serializers engines."); String serializedFiles = config.getJsonOutputPath()+"/"+this.buildId; this.engines.add(new CSVSerializerEngine(serializedFiles)); this.engines.add(new JSONFileSerializerEngine(serializedFiles)); } else { LOGGER.info("Files serializer won't be used"); } if (this.arguments.getString("mongoDBHost") != null) { LOGGER.info("Initialize mongoDB serializer engine."); MongoConnection mongoConnection = new MongoConnection(this.arguments.getString("mongoDBHost"), this.arguments.getString("mongoDBName")); if (mongoConnection.isConnected()) { this.engines.add(new MongoDBSerializerEngine(mongoConnection)); } else { LOGGER.error("Error while connecting to mongoDB."); } } else { LOGGER.info("MongoDB won't be used for serialization"); } } private void checkNopolSolverPath() { String solverPath = this.config.getZ3solverPath(); if (solverPath != null) { File file = new File(solverPath); if (!file.exists()) { System.err.println("The Nopol solver path should be an existing file: " + file.getPath() + " does not exist."); this.printUsage(); System.exit(-1); } } else { System.err.println("The Nopol solver path should be provided."); this.printUsage(); System.exit(-1); } } private void checkArguments() { if (!this.arguments.success()) { // print out specific error messages describing the problems for (java.util.Iterator<?> errs = arguments.getErrorMessageIterator(); errs.hasNext();) { System.err.println("Error: " + errs.next()); } this.printUsage(); } if (this.arguments.getBoolean("help")) { this.printUsage(); } } private void defineArgs() throws JSAPException { // Verbose output this.jsap = new JSAP(); // help Switch sw1 = new Switch("help"); sw1.setShortFlag('h'); sw1.setLongFlag("help"); sw1.setDefault("false"); this.jsap.registerParameter(sw1); // verbosity sw1 = new Switch("debug"); sw1.setShortFlag('d'); sw1.setLongFlag("debug"); sw1.setDefault("false"); this.jsap.registerParameter(sw1); FlaggedOption opt2 = new FlaggedOption("build"); opt2.setShortFlag('b'); opt2.setLongFlag("build"); opt2.setStringParser(JSAP.INTEGER_PARSER); opt2.setRequired(true); opt2.setHelp("Specify the build id to use."); this.jsap.registerParameter(opt2); String launcherModeValues = ""; for (LauncherMode mode : LauncherMode.values()) { launcherModeValues += mode.name() + ";"; } launcherModeValues.substring(0, launcherModeValues.length() - 2); // Launcher mode opt2 = new FlaggedOption("launcherMode"); opt2.setShortFlag('m'); opt2.setLongFlag("launcherMode"); opt2.setStringParser(EnumeratedStringParser.getParser(launcherModeValues)); opt2.setRequired(true); opt2.setHelp("Specify if RepairNator will be launch for repairing (REPAIR) or for collecting fixer builds (BEARS)."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("runId"); opt2.setLongFlag("runId"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify the runId for this launch."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("googleAccessToken"); opt2.setShortFlag('g'); opt2.setLongFlag("googleAccessToken"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify the google access token to use for serializers."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("spreadsheet"); opt2.setLongFlag("spreadsheet"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify Google Spreadsheet ID to put data."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("mongoDBHost"); opt2.setLongFlag("dbhost"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify mongodb host."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("mongoDBName"); opt2.setLongFlag("dbname"); opt2.setDefault("repairnator"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify mongodb DB name."); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("pushUrl"); opt2.setLongFlag("pushurl"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify repository to push data"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("z3"); opt2.setLongFlag("z3"); opt2.setDefault("./z3_for_linux"); opt2.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true)); opt2.setHelp("Specify path to Z3"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("outputPath"); opt2.setLongFlag("output"); opt2.setShortFlag('o'); opt2.setStringParser(FileStringParser.getParser().setMustBeDirectory(true).setMustExist(true)); opt2.setHelp("Specify path to output serialized files"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("workspace"); opt2.setLongFlag("workspace"); opt2.setShortFlag('w'); opt2.setDefault("./workspace"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify path to output serialized files"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("smtpServer"); opt2.setLongFlag("smtpServer"); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify SMTP server to use for Email notification"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("notifyto"); opt2.setLongFlag("notifyto"); opt2.setList(true); opt2.setListSeparator(','); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify email adresses to notify"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("ghLogin"); opt2.setLongFlag("ghLogin"); opt2.setRequired(true); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify login for Github use"); this.jsap.registerParameter(opt2); opt2 = new FlaggedOption("ghOauth"); opt2.setLongFlag("ghOauth"); opt2.setRequired(true); opt2.setStringParser(JSAP.STRING_PARSER); opt2.setHelp("Specify oauth for Github use"); this.jsap.registerParameter(opt2); } private void printUsage() { System.err.println("Usage: java <repairnator-pipeline name> [option(s)]"); System.err.println(); System.err.println("Options : "); System.err.println(); System.err.println(jsap.getHelp()); System.err.println("Please note that the following environment variables must be set: "); for (String env : Utils.ENVIRONMENT_VARIABLES) { System.err.println(" - " + env); } System.err.println("For using Nopol, you must add tools.jar in your classpath from your installed jdk"); System.exit(-1); } private void checkToolsLoaded() { URLClassLoader loader; try { loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); loader.loadClass("com.sun.jdi.AbsentInformationException"); } catch (ClassNotFoundException e) { System.err.println("Tools.jar must be loaded, here the classpath given for your app: "+System.getProperty("java.class.path")); this.printUsage(); System.exit(-1); } } private void getBuildToBeInspected() { Build buggyBuild = BuildHelper.getBuildFromId(this.buildId, null); String runId = this.arguments.getString("runId"); if (this.config.getLauncherMode() == LauncherMode.BEARS) { Build patchedBuild = BuildHelper.getNextBuildOfSameBranchOfStatusAfterBuild(buggyBuild, null); if (buggyBuild.getBuildStatus() == BuildStatus.FAILED) { this.buildToBeInspected = new BuildToBeInspected(buggyBuild, patchedBuild, ScannedBuildStatus.FAILING_AND_PASSING, runId); } else { this.buildToBeInspected = new BuildToBeInspected(buggyBuild, patchedBuild, ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES, runId); } } else { Build nextPassing = BuildHelper.getNextBuildOfSameBranchOfStatusAfterBuild(buggyBuild, BuildStatus.PASSED); if (nextPassing != null) { this.buildToBeInspected = new BuildToBeInspected(buggyBuild, nextPassing, ScannedBuildStatus.FAILING_AND_PASSING, runId); } else { this.buildToBeInspected = new BuildToBeInspected(buggyBuild, null, ScannedBuildStatus.ONLY_FAIL, runId); } } } private void mainProcess() throws IOException { LOGGER.info("Start by getting the build (buildId: "+this.buildId+") with the following config: "+this.config); this.getBuildToBeInspected(); HardwareInfoSerializer hardwareInfoSerializer = new HardwareInfoSerializer(this.engines, this.config.getRunId(), this.buildId+""); hardwareInfoSerializer.serialize(); List<AbstractDataSerializer> serializers = new ArrayList<>(); if (this.config.getLauncherMode() == LauncherMode.REPAIR) { serializers.add(new InspectorSerializer(this.engines)); serializers.add(new InspectorTimeSerializer(this.engines)); } else { serializers.add(new InspectorSerializer4Bears(this.engines)); serializers.add(new InspectorTimeSerializer4Bears(this.engines)); } serializers.add(new NopolSerializer(this.engines)); serializers.add(new MetricsSerializer(this.engines)); List<NotifierEngine> notifierEngines = new ArrayList<>(); if (this.arguments.getString("smtpServer") != null && this.arguments.getStringArray("notifyto") != null) { LOGGER.info("The email notifier engine will be used."); notifierEngines.add(new EmailNotifierEngine(this.arguments.getStringArray("notifyto"), this.arguments.getString("smtpServer"))); } else { LOGGER.info("The email notifier engine won't be used."); } List<AbstractNotifier> notifiers = new ArrayList<>(); notifiers.add(new PatchNotifier(notifierEngines)); notifiers.add(new FixerBuildNotifier(notifierEngines)); ProjectInspector inspector; if (config.getLauncherMode() == LauncherMode.BEARS) { inspector = new ProjectInspector4Bears(buildToBeInspected, this.config.getWorkspacePath(), serializers, notifiers); } else { inspector = new ProjectInspector(buildToBeInspected, this.config.getWorkspacePath(), serializers, notifiers); } inspector.run(); LOGGER.info("Inspector is finished. The process will now exit."); System.exit(0); } public static void main(String[] args) throws IOException, JSAPException { Launcher launcher = new Launcher(args); launcher.mainProcess(); } }
/* * EDACCView.java */ package edacc; import edacc.model.DatabaseConnector; import edacc.model.NoConnectionToDBException; import java.awt.Component; import java.sql.SQLException; import java.util.Observable; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observer; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import edacc.manageDB.Util; /** * The application's main frame. */ public class EDACCView extends FrameView implements Observer { private EDACCExperimentMode experimentMode; private EDACCManageDBMode manageDBMode; private EDACCNoMode noMode; private Component mode; private javax.swing.GroupLayout mainPanelLayout; public EDACCView(SingleFrameApplication app) { super(app); initComponents(); DatabaseConnector.getInstance().addObserver(this); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); statusAnimationLabel.setIcon(idleIcon); progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String) (evt.getNewValue()); statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer) (evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } }); experimentMode = new EDACCExperimentMode(); manageDBMode = new EDACCManageDBMode(); noMode = new EDACCNoMode(); mainPanelLayout = new javax.swing.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(noMode, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(noMode, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); mode = noMode; updateConnectionStateView(); SwingUtilities.invokeLater(new Runnable() { public void run() { btnConnectToDB(); } }); } private void createDatabaseErrorMessage(SQLException e) { javax.swing.JOptionPane.showMessageDialog(null, "There was an error while communicating with the database: " +e, "Connection error", javax.swing.JOptionPane.ERROR_MESSAGE); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = EDACCApp.getApplication().getMainFrame(); aboutBox = new EDACCAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } EDACCApp.getApplication().show(aboutBox); } /** 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() { mainPanel = new javax.swing.JPanel(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); connectToDBMenuItem = new javax.swing.JMenuItem(); disconnectMenuItem = new javax.swing.JMenuItem(); generateDBMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); gridMenu = new javax.swing.JMenu(); settingsMenuItem = new javax.swing.JMenuItem(); modusMenu = new javax.swing.JMenu(); manageDBModeMenuItem = new javax.swing.JRadioButtonMenuItem(); manageExperimentModeMenuItem = new javax.swing.JRadioButtonMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); statusPanel = new javax.swing.JPanel(); javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator(); statusMessageLabel = new javax.swing.JLabel(); statusAnimationLabel = new javax.swing.JLabel(); progressBar = new javax.swing.JProgressBar(); mainPanel.setMinimumSize(new java.awt.Dimension(800, 600)); mainPanel.setName("mainPanel"); // NOI18N org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 1006, Short.MAX_VALUE) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 630, Short.MAX_VALUE) ); menuBar.setAutoscrolls(true); menuBar.setName("menuBar"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getResourceMap(EDACCView.class); fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(edacc.EDACCApp.class).getContext().getActionMap(EDACCView.class, this); connectToDBMenuItem.setAction(actionMap.get("btnConnectToDB")); // NOI18N connectToDBMenuItem.setText(resourceMap.getString("connectToDBMenuItem.text")); // NOI18N connectToDBMenuItem.setName("connectToDBMenuItem"); // NOI18N fileMenu.add(connectToDBMenuItem); disconnectMenuItem.setAction(actionMap.get("btnDisconnect")); // NOI18N disconnectMenuItem.setText(resourceMap.getString("disconnectMenuItem.text")); // NOI18N disconnectMenuItem.setName("disconnectMenuItem"); // NOI18N fileMenu.add(disconnectMenuItem); generateDBMenuItem.setAction(actionMap.get("btnGenerateTables")); // NOI18N generateDBMenuItem.setText(resourceMap.getString("generateDBMenuItem.text")); // NOI18N generateDBMenuItem.setName("generateDBMenuItem"); // NOI18N fileMenu.add(generateDBMenuItem); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); gridMenu.setAction(actionMap.get("btnGridSettings")); // NOI18N gridMenu.setText(resourceMap.getString("gridMenu.text")); // NOI18N gridMenu.setName("gridMenu"); // NOI18N settingsMenuItem.setAction(actionMap.get("btnGridSettings")); // NOI18N settingsMenuItem.setText(resourceMap.getString("settingsMenuItem.text")); // NOI18N settingsMenuItem.setName("settingsMenuItem"); // NOI18N gridMenu.add(settingsMenuItem); menuBar.add(gridMenu); modusMenu.setText(resourceMap.getString("modusMenu.text")); // NOI18N modusMenu.setName("modusMenu"); // NOI18N manageDBModeMenuItem.setAction(actionMap.get("manageDBMode")); // NOI18N manageDBModeMenuItem.setText(resourceMap.getString("manageDBModeMenuItem.text")); // NOI18N manageDBModeMenuItem.setName("manageDBModeMenuItem"); // NOI18N modusMenu.add(manageDBModeMenuItem); manageExperimentModeMenuItem.setAction(actionMap.get("manageExperimentMode")); // NOI18N manageExperimentModeMenuItem.setText(resourceMap.getString("manageExperimentModeMenuItem.text")); // NOI18N manageExperimentModeMenuItem.setName("manageExperimentModeMenuItem"); // NOI18N modusMenu.add(manageExperimentModeMenuItem); menuBar.add(modusMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N jMenuItem1.setName("jMenuItem1"); // NOI18N helpMenu.add(jMenuItem1); menuBar.add(helpMenu); statusPanel.setName("statusPanel"); // NOI18N statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N statusMessageLabel.setName("statusMessageLabel"); // NOI18N statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N progressBar.setName("progressBar"); // NOI18N org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel); statusPanel.setLayout(statusPanelLayout); statusPanelLayout.setHorizontalGroup( statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1006, Short.MAX_VALUE) .add(statusPanelLayout.createSequentialGroup() .addContainerGap() .add(statusMessageLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 836, Short.MAX_VALUE) .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(statusAnimationLabel) .addContainerGap()) ); statusPanelLayout.setVerticalGroup( statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(statusPanelLayout.createSequentialGroup() .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(statusMessageLabel) .add(statusAnimationLabel) .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(3, 3, 3)) ); setComponent(mainPanel); setMenuBar(menuBar); setStatusBar(statusPanel); }// </editor-fold>//GEN-END:initComponents @Action public void btnConnectToDB() { if (databaseSettings == null) { JFrame mainFrame = EDACCApp.getApplication().getMainFrame(); databaseSettings = new EDACCDatabaseSettingsView(mainFrame, true); databaseSettings.setLocationRelativeTo(mainFrame); } EDACCApp.getApplication().show(databaseSettings); manageDBMode(); } @Action public void btnDisconnect() { try { DatabaseConnector.getInstance().disconnect(); } catch (SQLException ex) { JOptionPane.showMessageDialog(EDACCApp.getApplication().getMainFrame(), "An error occured while closing the database connection: \n" + ex.getMessage(), "Couldn't close database connection", JOptionPane.ERROR_MESSAGE); } finally { noMode(); } } @Action public void btnGenerateTables() { if (JOptionPane.showConfirmDialog(mode, "This will destroy the EDACC tables of your DB an create new ones. Do you wish to continue?", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { try { // User clicked on "Yes" DatabaseConnector.getInstance().createDBSchema(); } catch (NoConnectionToDBException ex) { JOptionPane.showMessageDialog(mode, "Couldn't generate the EDACC tables: No connection to database. Please connect to a database first.", "Error!", JOptionPane.ERROR_MESSAGE); } catch (SQLException ex) { JOptionPane.showMessageDialog(mode, "An error occured while trying to generate the EDACC tables: " + ex.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE); } finally { noMode(); } } } public void noMode() { manageExperimentModeMenuItem.setSelected(false); manageDBModeMenuItem.setSelected(false); mainPanelLayout.replace(mode, noMode); mode = noMode; } @Action public void manageDBMode() { /**if (!manageDBModeMenuItem.isSelected()) { noMode(); return; }*/ if (manageExperimentModeMenuItem.isSelected()) { manageExperimentModeMenuItem.setSelected(false); } try { manageDBMode.initialize(); mainPanelLayout.replace(mode, manageDBMode); mode = manageDBMode; manageDBModeMenuItem.setSelected(true); } catch (NoConnectionToDBException ex) { JOptionPane.showMessageDialog(this.getComponent(), "You have to connect to the database before switching modes", "No database connection", JOptionPane.ERROR_MESSAGE); noMode(); } catch (SQLException ex) { createDatabaseErrorMessage(ex); noMode(); } } @Action public void manageExperimentMode() { if (!manageExperimentModeMenuItem.isSelected()) { noMode(); return; } if (manageDBModeMenuItem.isSelected()) { if (JOptionPane.showConfirmDialog(mode, "Any unsaved changes will be lost, are you sure you want to switch to experiment mode?", "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) { manageDBModeMenuItem.setSelected(false); Util.clearCaches(); } else { return; } } try { experimentMode.initialize(); mainPanelLayout.replace(mode, experimentMode); mode = experimentMode; manageExperimentModeMenuItem.setSelected(true); } catch (NoConnectionToDBException ex) { JOptionPane.showMessageDialog(this.getComponent(), "You have to connect to the database before switching modes", "No database connection", JOptionPane.ERROR_MESSAGE); noMode(); } catch (SQLException ex) { createDatabaseErrorMessage(ex); noMode(); } } @Action public void btnGridSettings() { if (gridSettings == null) { JFrame mainFrame = EDACCApp.getApplication().getMainFrame(); gridSettings = new EDACCGridSettingsView(mainFrame, true); gridSettings.setLocationRelativeTo(mainFrame); } try { gridSettings.loadSettings(); EDACCApp.getApplication().show(gridSettings); } catch (NoConnectionToDBException e) { JOptionPane.showMessageDialog(this.getComponent(), "Couldn't load settings. No connection to database", "No database connection", JOptionPane.ERROR_MESSAGE); } catch (SQLException e) { JOptionPane.showMessageDialog(this.getComponent(), "Error while loading settings: \n" + e.getMessage(), "Error loading settings", JOptionPane.ERROR_MESSAGE); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem connectToDBMenuItem; private javax.swing.JMenuItem disconnectMenuItem; private javax.swing.JMenuItem generateDBMenuItem; private javax.swing.JMenu gridMenu; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JPanel mainPanel; private javax.swing.JRadioButtonMenuItem manageDBModeMenuItem; private javax.swing.JRadioButtonMenuItem manageExperimentModeMenuItem; private javax.swing.JMenuBar menuBar; private javax.swing.JMenu modusMenu; private javax.swing.JProgressBar progressBar; private javax.swing.JMenuItem settingsMenuItem; private javax.swing.JLabel statusAnimationLabel; private javax.swing.JLabel statusMessageLabel; private javax.swing.JPanel statusPanel; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; private JDialog databaseSettings; private EDACCGridSettingsView gridSettings; public void update(Observable o, Object arg) { // watch connection state updateConnectionStateView(); } /** * Updates the GUI components which are sensitive on the DB connection state. */ private void updateConnectionStateView() { boolean state = DatabaseConnector.getInstance().isConnected(); connectToDBMenuItem.setEnabled(!state); disconnectMenuItem.setEnabled(state); generateDBMenuItem.setEnabled(state); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.stuy; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Servo; /** * 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 WCDBot extends IterativeRobot { public static final int FRONT_LEFT_MOTOR = 1; public static final int REAR_LEFT_MOTOR = 2; public static final int FRONT_RIGHT_MOTOR = 3; public static final int REAR_RIGHT_MOTOR = 4; public static final int LEFT_GEAR_SHIFT = 5; public static final int RIGHT_GEAR_SHIFT = 6; public static final int GAMEPAD_PORT = 1; RobotDrive drive; Servo leftShift, rightShift; Joystick gamepad; // TODO: implement gear switching (PWM ports 5 left and 6 right) /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { drive = new RobotDrive(FRONT_LEFT_MOTOR, REAR_LEFT_MOTOR, FRONT_RIGHT_MOTOR, REAR_RIGHT_MOTOR); leftShift = new Servo(LEFT_GEAR_SHIFT); rightShift = new Servo(RIGHT_GEAR_SHIFT); gamepad = new Joystick(GAMEPAD_PORT); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /** * This function is called periodically during operator control */ public void teleopPeriodic() { drive.tankDrive(gamepad, 2, gamepad, 4); if (gamepad.getRawButton(9)) { leftShift.set(0); rightShift.set(0); } else if (gamepad.getRawButton(10)) { leftShift.set(1); rightShift.set(1); } } }
package graphics.nim.volterra; import java.util.HashMap; import graphics.nim.volterra.util.Matrix4f; import static org.lwjgl.opengl.GL20.*; public class Shader { public int handle; private HashMap<String, Integer> locationMap = new HashMap<String, Integer>(); public Shader(int handle) { this.handle = handle; } public void bind() { glUseProgram(handle); } public void unbind() { glUseProgram(0); } public int location(String name) { Integer location = locationMap.get(name); if (location == null) { location = glGetUniformLocation(handle, name); locationMap.put(name, location); } return location; } public void uniform1f(String name, float value) { glUniform1f(location(name), value); } public void uniform3f(String name, float v0, float v1, float v2) { glUniform3f(location(name), v0, v1, v2); } public void uniformMatrix4f(String name, Matrix4f m) { glUniformMatrix4fv(location(name), false, m.getBuffer()); } }
package edu.berkeley.cs.amplab.smash4j; import static edu.berkeley.cs.amplab.smash4j.TestUtils.getReference; import static edu.berkeley.cs.amplab.smash4j.TestUtils.variant; import static edu.berkeley.cs.amplab.smash4j.TestUtils.variants; import static edu.berkeley.cs.amplab.smash4j.VariantEvaluator.Genotype.HET; import static edu.berkeley.cs.amplab.smash4j.VariantEvaluator.Genotype.HOM_VAR; import static edu.berkeley.cs.amplab.smash4j.VariantEvaluator.VariantType.INDEL_DELETION; import static edu.berkeley.cs.amplab.smash4j.VariantEvaluator.VariantType.SNP; import static edu.berkeley.cs.amplab.smash4j.VariantEvaluator.VariantType.SV_INSERTION; import static org.junit.Assert.assertEquals; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import org.junit.BeforeClass; import org.junit.Test; import edu.berkeley.cs.amplab.fastaparser.FastaReader; import edu.berkeley.cs.amplab.smash4j.Smash4J.VariantProto; import edu.berkeley.cs.amplab.smash4j.VariantEvaluator.GenotypeConcordance; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.NavigableMap; public class VariantEvaluatorTest { private static File reference; private static VariantEvaluator.ContigStats contigStats(String contig, NavigableMap<Integer, VariantProto> trueVariants, NavigableMap<Integer, VariantProto> predictedVariants, Iterable<Integer> truePositiveLocations, Iterable<Integer> falsePositiveLocations, Iterable<Integer> falseNegativeLocations, Iterable<Integer> incorrectPredictions, GenotypeConcordance concordance) { return VariantEvaluator.ContigStats.create(contig, trueVariants, predictedVariants, truePositiveLocations, falsePositiveLocations, falseNegativeLocations, incorrectPredictions, concordance, 50); } private static Map<String, VariantEvaluator.ContigStats> evaluate( final Iterable<VariantProto> trueVariants, final Iterable<VariantProto> predictedVariants) throws Exception { return evaluate(trueVariants, predictedVariants, Optional.<Iterable<VariantProto>>absent()); } private static Map<String, VariantEvaluator.ContigStats> evaluate( final Iterable<VariantProto> trueVariants, final Iterable<VariantProto> predictedVariants, final Iterable<VariantProto> knownFalsePositives) throws Exception { return evaluate(trueVariants, predictedVariants, Optional.of(knownFalsePositives)); } private static Map<String, VariantEvaluator.ContigStats> evaluate( final Iterable<VariantProto> trueVariants, final Iterable<VariantProto> predictedVariants, final Optional<Iterable<VariantProto>> knownFalsePositives) throws Exception { return FastaReader.create(reference).read( new FastaReader.Callback<Map<String, VariantEvaluator.ContigStats>>() { @Override public Map<String, VariantEvaluator.ContigStats> read(Map<String, Integer> info, FastaReader.Callback.FastaFile reference) throws Exception { return VariantEvaluator.builder() .setMaxSvBreakpointDistance(100) .setMaxVariantLengthDifference(100) .setReference(reference) .setRescueWindowSize(50) .build() .evaluate(trueVariants, predictedVariants, knownFalsePositives); } }); } @BeforeClass public static void setUp() throws IOException { reference = getReference(); } @Test public void testChromEvaluateGenotypeConcordance() throws Exception { NavigableMap<Integer, VariantProto> trueVariants = variants( variant("chr1", 2, "A", "T", "0/1"), variant("chr1", 5, "C", "T", "0/1"), variant("chr1", 9, "A", "G", "1/1")), predictedVariants = variants( variant("chr1", 2, "A", "T", "1/1"), variant("chr1", 6, "C", "G", "0/1"), variant("chr1", 9, "A", "G", "1/1")); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants, Arrays.asList(2, 9), Arrays.asList(6), Arrays.asList(5), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SNP, HET, HOM_VAR) .increment(SNP, HOM_VAR, HOM_VAR))), evaluate(trueVariants.values(), predictedVariants.values())); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants = variants( variant("chr1", 2, "A", "T", "0|1"), variant("chr1", 9, "A", "G", "1|1")), predictedVariants = variants( variant("chr1", 2, "A", "T", "1|0"), variant("chr1", 9, "A", "G", "1|1")), Arrays.asList(2, 9), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SNP, HET, HET) .increment(SNP, HOM_VAR, HOM_VAR))), evaluate(trueVariants.values(), predictedVariants.values())); } @Test public void testChromEvaluateVariantsKnownFP() throws Exception { NavigableMap<Integer, VariantProto> trueVariants = variants( variant("chr1", 2, "A", "T", "0/1")), predictedVariants = variants( variant("chr1", 2, "A", "T", "0/1"), variant("chr1", 4, "G", "C", "1/1"), variant("chr1", 7, "G", "A", "0/1")), knownFalsePositives = variants( variant("chr1", 1, "A", "T", "./."), variant("chr1", 7, "G", Collections.<String>emptyList(), "0/0")); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants, Arrays.asList(2), Arrays.asList(4, 7), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SNP, HET, HET)) .setKnownFalsePositives(knownFalsePositives, Arrays.asList(7), Arrays.asList(7))), evaluate(trueVariants.values(), predictedVariants.values(), knownFalsePositives.values())); } @Test public void testChromEvaluateVariantsSV() throws Exception { NavigableMap<Integer, VariantProto> trueVariants = variants(variant("chr1", 6, "C", "CGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGAAAAA", "0/1")), predictedVariants = variants(variant("chr1", 6, "C", "CGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGAAAAA", "0/1")); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants, Arrays.asList(6), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SV_INSERTION, HET, HET))), evaluate(trueVariants.values(), predictedVariants.values())); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants = variants(variant("chr1", 6, "C", "CGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGAAAAATGC", "0/1")), Arrays.asList(6), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SV_INSERTION, HET, HET))), evaluate(trueVariants.values(), predictedVariants.values())); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants = variants(variant("chr1", 4, "C", "CGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGAAAAA", "0/1")), Arrays.asList(6), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(SV_INSERTION, HET, HET))), evaluate(trueVariants.values(), predictedVariants.values())); assertEquals( ImmutableMap.of( "chr1", contigStats( "chr1", trueVariants, predictedVariants = variants(variant("chr1", 110, "C", "CGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGACGTGAGATGAAAAA", "0/1")), Collections.<Integer>emptyList(), Arrays.asList(110), Arrays.asList(6), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create())), evaluate(trueVariants.values(), predictedVariants.values())); } @Test public void testRescueChromEvalVariants() throws Exception { VariantProto rescuedVariant = variant("chr2", 3, "GCCG", "GCA", "1/1"); NavigableMap<Integer, VariantProto> trueVariants = variants(rescuedVariant), predictedVariants = variants( variant("chr2", 3, "GC", "G", "1/1"), variant("chr2", 6, "G", "A", "1/1")); assertEquals( ImmutableMap.of( "chr2", contigStats( "chr2", trueVariants, predictedVariants, Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Arrays.asList(3), VariantEvaluator.GenotypeConcordance.create()) .setRescuedVariants(variants(rescuedVariant))), evaluate(trueVariants.values(), predictedVariants.values())); } @Test public void testRescueTruePosChromEvaluateVariants() throws Exception { VariantProto rescuedVariant1 = variant("chr4", 3, "TC", "T", "1/1"), rescuedVariant2 = variant("chr4", 8, "C", "T", "1/1"); NavigableMap<Integer, VariantProto> trueVariants = variants( rescuedVariant1, variant("chr4", 5, "TC", "T", "1/1"), rescuedVariant2), predictedVariants = variants( variant("chr4", 4, "C", "T", "1/1"), variant("chr4", 5, "TC", "T", "1/1"), variant("chr4", 7, "TC", "T", "1/1")); assertEquals( ImmutableMap.of( "chr4", contigStats( "chr4", trueVariants, predictedVariants, Arrays.asList(5), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), Collections.<Integer>emptyList(), VariantEvaluator.GenotypeConcordance.create() .increment(INDEL_DELETION, HOM_VAR, HOM_VAR)) .setRescuedVariants(variants(rescuedVariant1, rescuedVariant2))), evaluate(trueVariants.values(), predictedVariants.values())); } }
package it.cybion.socialeyeser; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import org.joda.time.DateTime; import org.joda.time.Interval; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; import java.util.LinkedList; import java.util.Queue; import static org.testng.Assert.assertTrue; /** * @author Matteo Moci ( matteo (dot) moci (at) gmail (dot) com ) */ public class TrendTestCase { private static final Logger LOGGER = LoggerFactory.getLogger(TrendTestCase.class); @Test public void shouldTestSingletonEventBus() throws Exception { final EventBus eventBus = new EventBus(); final TweetArrivedListener tweetArrivedListener = new TweetArrivedListener(); eventBus.register(tweetArrivedListener); final long tenMsecsPauseBetweenTweets = 10L; final TweetStream tweetStream = new TweetStream(tenMsecsPauseBetweenTweets, eventBus); final Thread producerThread = new Thread(tweetStream); producerThread.start(); final long oneSecMsecs = 1000L; Thread.sleep(oneSecMsecs); tweetStream.stop(); producerThread.join(); assertTrue(true); } private static class TweetArrivedListener { private final Queue<DateTime> lastRequests; private int maxTweetsPerWindow; private int windowSizeMsecs; private TweetArrivedListener() { this.lastRequests = new LinkedList<DateTime>(); this.maxTweetsPerWindow = 10; this.windowSizeMsecs = 100; } @Subscribe public void recordTweet(final TweetArrived event) { final DateTime timeStamp = event.getTimeStamp(); boolean trendDetected = areLastEventsEnoughForTrend(timeStamp); if (trendDetected) { LOGGER.info("it's trending! - " + timeStamp); } else { LOGGER.info("nothing relevant " + timeStamp); } } private boolean areLastEventsEnoughForTrend(final DateTime timestamp) { //update this.lastRequests.add(timestamp); removeLastElementIfExceeds(maxTweetsPerWindow); final DateTime oldest = this.lastRequests.peek(); if (oldest != null) { Interval interval = new Interval(oldest, timestamp); if (interval.toDurationMillis() >= windowSizeMsecs) { LOGGER.info("interval " + interval.toDurationMillis() + " msec"); return true; } } return false; } private void removeLastElementIfExceeds(int maxTweetsPerWindow) { //check if (this.lastRequests.size() >= maxTweetsPerWindow) { final DateTime removed = this.lastRequests.poll(); } } } private static class TweetArrived { private String tweetId; private DateTime timeStamp; public TweetArrived(final String tweetId, final DateTime timeStamp) { this.tweetId = tweetId; this.timeStamp = timeStamp; } public String getTweetId() { return tweetId; } public DateTime getTimeStamp() { return timeStamp; } } private static class TweetStream implements Runnable { private final EventBus eventBus; private Long pauseBetweenTweets; private boolean running = true; public TweetStream(Long pauseBetweenTweets, EventBus eventBus) { this.pauseBetweenTweets = pauseBetweenTweets; this.eventBus = eventBus; } @Override public void run() { while (running) { final DateTime now = new DateTime(); final TweetArrived aTweetArrived = new TweetArrived("" + now.getMillis(), now); this.eventBus.post(aTweetArrived); try { Thread.sleep(pauseBetweenTweets); } catch (InterruptedException e) { e.printStackTrace(); } } } public void stop() { this.running = false; } } }
package gov.nih.nci.evs.reportwriter.service; import java.io.*; import java.util.*; import gov.nih.nci.evs.reportwriter.bean.*; import gov.nih.nci.evs.reportwriter.formatter.*; import gov.nih.nci.evs.reportwriter.utils.*; import org.LexGrid.commonTypes.*; import org.LexGrid.concepts.*; import org.apache.log4j.*; import org.lexgrid.valuesets.*; import gov.nih.nci.evs.reportwriter.properties.*; import gov.nih.nci.evs.utils.*; import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept; /** * @author EVS Team (Kim Ong, David Yee) * @version 1.0 */ public class ReportGenerationThread implements Runnable { private static Logger _logger = Logger .getLogger(ReportGenerationThread.class); private String _outputDir = null; private String _standardReportLabel = null; private String _uid = null; private String _emailAddress = null; private int[] _ncitColumns = new int[] {}; private int _count = 0; private String _hierarchicalAssoName = null; private int _abortLimit = 0; private HashMap _code2PTHashMap = null; SpecialCases.CDISCExtensibleInfo _cdiscInfo = null; private String prev_subset_code = null; private boolean subheader_line_required = false; ReportColumn[] temp_cols = null; public ReportGenerationThread(String outputDir, String standardReportLabel, String uid, String emailAddress, int[] ncitColumns) { _outputDir = outputDir; _standardReportLabel = standardReportLabel; _uid = uid; _emailAddress = emailAddress; _ncitColumns = ncitColumns; _count = 0; _code2PTHashMap = new HashMap(); } public Boolean warningMsg(StringBuffer buffer, String text) { buffer.append(text); _logger.warn(text); return Boolean.FALSE; } public PrintWriter openPrintWriter(String outputfile) { try { PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(outputfile))); return pw; } catch (Exception e) { e.printStackTrace(); return null; } } public void closePrintWriter(PrintWriter pw) { if (pw == null) { _logger.warn("PrintWriter is not open."); return; } pw.close(); pw = null; } public void run() { _logger.info("Generating report -- please wait..."); StringBuffer warningMsg = new StringBuffer(); Date startDate = new Date(); StopWatch stopWatch = new StopWatch(); Boolean successful = true; try { successful = generateStandardReport(_outputDir, _standardReportLabel, _uid, warningMsg); long runTime = stopWatch.getDuration(); emailNotification(successful, _standardReportLabel, warningMsg, startDate, new Date(), runTime); _logger.info("Report " + _standardReportLabel + " generated."); _logger.info(" * Start time: " + startDate); _logger.info(" * Run time: " + stopWatch.getResult(runTime)); } catch (Exception e) { warningMsg.append("\n" + ExceptionUtils.getStackTrace(e)); long runTime = stopWatch.getDuration(); emailNotification(false, _standardReportLabel, warningMsg, startDate, new Date(), runTime); ExceptionUtils.print(_logger, e, "* In ReportGenerationThread.run"); e.printStackTrace(); } } private void emailNotification(boolean successful, String standardReportLabel, StringBuffer warningMsg, Date startDate, Date endDate, long runTime) { try { if (_emailAddress == null || _emailAddress.length() <= 0) { _logger.warn("Email notification is not sent for report " + _standardReportLabel + "."); _logger.warn(" * email address not set."); return; } String mailServer = AppProperties.getInstance().getProperty( AppProperties.MAIL_SMTP_SERVER); String from = _emailAddress; String recipients = _emailAddress; String subject = ""; StringBuffer message = new StringBuffer(); boolean displaySummary = false; if (displaySummary) { message.append(_standardReportLabel + ", " + StopWatch.format(StopWatch.timeInMinutes(runTime)) + " minutes, " + _count + " rows\n"); message.append("\n"); message.append(StringUtils.SEPARATOR + "\n"); } if (successful) { subject = "Generated: " + _standardReportLabel + "..."; message.append(_standardReportLabel + " is generated.\n"); } else { subject = "Failed generating: " + _standardReportLabel + "..."; message.append(_standardReportLabel + " failed to generated.\n"); message.append(warningMsg + "\n"); } message.append("\n"); message.append(StringUtils.SEPARATOR + "\n"); message.append("LexEVS: " + AppProperties.getInstance().getProperty( AppProperties.EVS_SERVICE_URL) + "\n"); message.append("Started: " + startDate + "\n"); message.append("Completed: " + endDate + "\n"); message.append("Report generation time: \n"); message.append(" * In hours: " + StopWatch.format(StopWatch.timeInHours(runTime)) + "\n"); message.append(" * In minutes: " + StopWatch.format(StopWatch.timeInMinutes(runTime)) + "\n"); message.append("Total number of concepts processed: " + _count + "\n"); message.append("\n"); message.append(StringUtils.SEPARATOR + "\n"); message.append("Report Template Parameters:\n"); try { StandardReportTemplate standardReportTemplate = null; standardReportTemplate = getStandardReportTemplate( standardReportLabel, warningMsg); message.append(" * Label: " + standardReportTemplate.getLabel() + "\n"); message.append(" * Coding Scheme Name: " + standardReportTemplate.getCodingSchemeName() + "\n"); message.append(" * Coding Scheme Version: " + standardReportTemplate.getCodingSchemeVersion() + "\n"); message.append(" * Root Concept Code: " + standardReportTemplate.getRootConceptCode() + "\n"); message.append(" * Association Name: " + standardReportTemplate.getAssociationName() + "\n"); Boolean dirValue = standardReportTemplate.getDirection(); String dirStr = dirValue ? "Target" : "Source"; message.append(" * Direction: " + dirStr + "(" + dirValue + ")" + "\n"); message.append(" * Level: " + standardReportTemplate.getLevel() + "\n"); } catch (Exception e) { message.append(" * Exception: " + e.getMessage() + "\n"); } boolean send = true; MailUtils.postMail(mailServer, from, recipients, subject, message.toString(), send); } catch (Exception e) { ExceptionUtils.print(_logger, e); e.printStackTrace(); } } private StandardReportTemplate getStandardReportTemplate( String standardReportLabel, StringBuffer warningMsg) throws Exception { StandardReportTemplate standardReportTemplate = null; SDKClientUtil sdkclientutil = new SDKClientUtil(); String FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate"; String methodName = "setLabel"; Object obj = sdkclientutil.search(FQName, methodName, standardReportLabel); standardReportTemplate = (StandardReportTemplate) obj; _logger.debug("standardReportTemplate ID: " + standardReportTemplate.getId()); _logger.debug("standardReportTemplate label: " + standardReportTemplate.getLabel()); return standardReportTemplate; } public Boolean generateStandardReport(String outputDir, String standardReportLabel, String uid, StringBuffer warningMsg) { StandardReportTemplate standardReportTemplate = null; try { standardReportTemplate = getStandardReportTemplate( standardReportLabel, warningMsg); } catch (Exception e) { return warningMsg(warningMsg, "Unable to identify report label " + standardReportLabel + " -- report not generated."); } try { String defining_set_desc = standardReportTemplate.getRootConceptCode(); if (defining_set_desc.indexOf("|") != -1) { return generateSpecialReport(outputDir, standardReportLabel, uid, warningMsg); } _logger.debug(StringUtils.SEPARATOR); _logger.debug("Method: generateStandardReport"); _logger.debug(" * Output directory: " + outputDir); _logger.debug(" * standardReportLabel: " + standardReportLabel); _logger.debug(" * uid: " + uid); File dir = new File(outputDir); if (!dir.exists()) { _logger.debug("Output directory " + outputDir + " does not exist -- try to create the directory."); boolean retval = dir.mkdir(); if (!retval) { throw new Exception("Unable to create output directory " + outputDir + " - please check privilege setting."); } else { _logger.debug("Output directory: " + outputDir + " created."); } } else { _logger.debug("Output directory: " + outputDir + " exists."); } String version = standardReportTemplate.getCodingSchemeVersion(); // append version to the report file name: String pathname = outputDir + File.separator + standardReportLabel + "__" + version + ".txt"; pathname = pathname.replaceAll(" ", "_"); _logger.debug("Full path name: " + pathname); PrintWriter pw = openPrintWriter(pathname); if (pw == null) throw new Exception("Unable to create output file " + pathname + " -- please check privilege setting."); _logger.debug("opened PrintWriter " + pathname); int id = standardReportTemplate.getId(); String label = standardReportTemplate.getLabel(); String codingSchemeName = standardReportTemplate.getCodingSchemeName(); String codingSchemeVersion = standardReportTemplate.getCodingSchemeVersion(); String rootConceptCode = standardReportTemplate.getRootConceptCode(); String associationName = standardReportTemplate.getAssociationName(); boolean direction = standardReportTemplate.getDirection(); int level = standardReportTemplate.getLevel(); Character delimiter = standardReportTemplate.getDelimiter(); String delimeter_str = "\t"; _logger.debug(StringUtils.SEPARATOR); _logger.debug(" * ID: " + id); _logger.debug(" * Label: " + label); _logger.debug(" * CodingSchemeName: " + codingSchemeName); _logger.debug(" * CodingSchemeVersion: " + codingSchemeVersion); _logger.debug(" * Root: " + rootConceptCode); _logger.debug(" * AssociationName: " + associationName); _logger.debug(" * Direction: " + direction); _logger.debug(" * Level: " + level); _logger.debug(" * Delimiter: " + delimiter); Object[] objs = null; Collection<ReportColumn> cc = standardReportTemplate.getColumnCollection(); if (cc == null) { throw new Exception( "standardReportTemplate.getColumnCollection" + " returns null???"); } else { objs = cc.toArray(); } ReportColumn[] cols = null; if (cc != null) { cols = new ReportColumn[objs.length]; temp_cols = new ReportColumn[objs.length]; for (int i = 0; i < objs.length; i++) { gov.nih.nci.evs.reportwriter.bean.ReportColumn col = (gov.nih.nci.evs.reportwriter.bean.ReportColumn) objs[i]; Debug.print(col); cols[i] = col; } } temp_cols = copyReportColumns(cols); setReportColumns(temp_cols); _logger.debug(StringUtils.SEPARATOR); _logger.debug("* Start generating report..." + pathname); printReportHeading(pw, cols); String scheme = standardReportTemplate.getCodingSchemeName(); version = standardReportTemplate.getCodingSchemeVersion(); String code = standardReportTemplate.getRootConceptCode(); Entity defining_root_concept = DataUtils.getConceptByCode(codingSchemeName, codingSchemeVersion, null, rootConceptCode); associationName = standardReportTemplate.getAssociationName(); // associationName = "A8"; //NOTE_A8: A8 vs Concept_In_Subset level = standardReportTemplate.getLevel(); String tag = null; int curr_level = 0; int max_level = standardReportTemplate.getLevel(); if (max_level < 0) max_level = AppProperties.getInstance().getIntProperty( AppProperties.MAXIMUM_LEVEL, 20); // printReportHeading(pw, cols); if (_hierarchicalAssoName == null) { Vector<String> hierarchicalAssoName_vec = DataUtils.getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0) { return Boolean.FALSE; } _hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); } String associationCode = ""; try { associationCode = DataUtils.getAssociationCode(codingSchemeName, codingSchemeVersion, associationName); } catch (Exception e) { throw new Exception( "Unable to create output file " + pathname + " - could not map association name to its corresponding code."); } _cdiscInfo = new SpecialCases.CDISCExtensibleInfo(cols); LexEVSValueSetDefinitionServices definitionServices = DataUtils.getValueSetDefinitionService(); String uri = DataUtils.codingSchemeName2URI(scheme, version); traverse(definitionServices, uri, pw, scheme, version, tag, defining_root_concept, code, _hierarchicalAssoName, associationName, direction, curr_level, max_level, cols); closePrintWriter(pw); _logger.debug("Total number of concepts processed: " + _count); _logger.debug("Output file " + pathname + " generated."); return createStandardReports(outputDir, standardReportLabel, uid, standardReportTemplate, pathname, version, delimeter_str); } catch (Exception e) { return warningMsg(warningMsg, ExceptionUtils.getStackTrace(e)); } } public void printReportHeading(PrintWriter pw, ReportColumn[] cols) { if (cols == null) { _logger.warn("In printReportHeading number of ReportColumn:" + " cols == null ??? "); } String columnHeadings = ""; String delimeter_str = "\t"; if (cols == null) { return; } for (int i = 0; i < cols.length; i++) { ReportColumn rc = (ReportColumn) cols[i]; String label = rc.getLabel(); columnHeadings = columnHeadings + label; if (i < cols.length - 1) columnHeadings = columnHeadings + delimeter_str; } pw.println(columnHeadings); } private void writeColumnData(LexEVSValueSetDefinitionServices definitionServices, String uri, PrintWriter pw, String scheme, String version, Entity defining_root_concept, Entity associated_concept, Entity c, String delim, ReportColumn[] cols, boolean firstColRequired) throws Exception { if (firstColRequired) { String firstValue = get_ReportColumnValue(definitionServices, uri, scheme, version, defining_root_concept, associated_concept, c, cols[0]); if (firstValue == null) return; firstValue = firstValue.trim(); if (firstValue.length() == 0) return; } String output_line = ""; for (int i = 0; i < cols.length; i++) { ReportColumn rc = (ReportColumn) cols[i]; String s = //KLO get_ReportColumnValue(definitionServices, uri, scheme, version, defining_root_concept, associated_concept, c, rc); if (i == 0) { output_line = s; } else { // output_line = output_line + "\t" + s; output_line = output_line + delim + s; } } pw.println(output_line); _count++; if ((_count / 100) * 100 == _count) { _logger.debug("Number of concepts processed: " + _count); } } private void writeColumnData(LexEVSValueSetDefinitionServices definitionServices, String uri, PrintWriter pw, String scheme, String version, Entity defining_root_concept, Entity associated_concept, Entity c, String delim, ReportColumn[] cols) throws Exception { Vector<String> values = new Vector<String>(); // _cdiscInfo.isExtensibleValue = false; if (associated_concept.getEntityCode().compareTo(c.getEntityCode()) == 0) { _logger.debug("(*********) adding subset line..." + c.getEntityCode()); } for (int i = 0; i < cols.length; i++) { ReportColumn rc = (ReportColumn) cols[i]; String value = get_ReportColumnValue(definitionServices, uri, scheme, version, defining_root_concept, associated_concept, c, rc); /* if (SpecialCases.CDISC.ON && SpecialCases.CDISC.writeExtensibleColumnData(_cdiscInfo, rc, values, value, i)) { if (_cdiscInfo.skipRow) return; value = _cdiscInfo.newValue; } */ if (value == null) value = ""; values.add(value); //_logger.debug("add value: " + value); } /* if (SpecialCases.CDISC.ON) { SpecialCases.CDISC.writeSubheader( definitionServices, uri, _cdiscInfo, this, values, pw, scheme, version, defining_root_concept, associated_concept, c, delim, cols); } */ pw.println(StringUtils.toString(values, delim, true)); _count++; if ((_count / 100) * 100 == _count) { _logger.debug("Number of concepts processed: " + _count); } } private void traverse(LexEVSValueSetDefinitionServices definitionServices, String uri, PrintWriter pw, String scheme, String version, String tag, Entity defining_root_concept, String code, String hierarchyAssociationName, String associationName, boolean direction, int level, int maxLevel, ReportColumn[] cols) throws Exception { if (_abortLimit > 0 && _count > _abortLimit) return; if (maxLevel != -1 && level > maxLevel) return; Entity root = DataUtils.getConceptByCode(scheme, version, tag, code); if (root == null) { _logger.warn("Concept with code " + code + " not found."); return; } else { _logger.debug("Level: " + level + " Subset: " + root.getEntityCode()); } String delim = "\t"; Vector<Entity> v = new Vector<Entity>(); if (direction) { v = DataUtils.getAssociationTargets(definitionServices, uri, scheme, version, root.getEntityCode(), associationName); } else { v = DataUtils.getAssociationSources(definitionServices, uri, scheme, version, root.getEntityCode(), associationName); } //Boolean isForwardNavigable = DataUtils.getIsForwardNavigable(scheme, version); //String[] asso_array = DataUtils.getHierarchyAssociations(scheme, version); //Vector<Entity> v = DataUtils.getSubconcepts(scheme, version, code); // associated concepts (i.e., concepts in subset) if (v == null) return; _logger.debug("Subset size: " + v.size()); _logger.debug("prev_subset_code: " + prev_subset_code); _logger.debug("root.getEntityCode(): " + root.getEntityCode()); if (subheader_line_required && prev_subset_code != null && root.getEntityCode().compareTo(prev_subset_code) != 0) { _logger.debug("(**********) calling writeColumnData using temp_cols ..." + root.getEntityCode()); writeColumnData(definitionServices, uri, pw, scheme, version, defining_root_concept, root, root, delim, temp_cols); prev_subset_code = root.getEntityCode(); _logger.debug("setting prev_subset_code to: " + root.getEntityCode()); } for (int i = 0; i < v.size(); i++) { // subset member element Entity c = (Entity) v.elementAt(i); writeColumnData(definitionServices, uri, pw, scheme, version, defining_root_concept, root, c, delim, cols); if (_abortLimit > 0 && _count > _abortLimit) break; } // Note: Commented on 2/24/10 (Wed). subconcept_vec size was 0. // Vector<Entity> subconcept_vec = // DataUtils.getAssociationTargets(scheme, version, root // .getEntityCode(), hierarchyAssociationName); Vector<String> subconcept_vec = DataUtils .getSubconceptCodes2(scheme, version, root.getEntityCode()); //Vector<Entity> subconcept_vec = DataUtils.getSubconcepts(scheme, version, code); if (subconcept_vec == null | subconcept_vec.size() == 0) return; level++; for (int k = 0; k < subconcept_vec.size(); k++) { // Note: Commented on 2/24/10 (Wed). subconcept_vec size was 0. // Entity concept = (Entity) subconcept_vec.elementAt(k); //String subconcep_code = concept.getEntityCode(); //Entity e = (Entity) subconcept_vec.elementAt(k); String subconcep_code = subconcept_vec.elementAt(k); traverse(definitionServices, uri, pw, scheme, version, tag, defining_root_concept, subconcep_code, hierarchyAssociationName, associationName, direction, level, maxLevel, cols); } } /* public String getReportColumnValue(LexEVSValueSetDefinitionServices definitionServices, String uri, String scheme, String version, Entity defining_root_concept, Entity associated_concept, Entity node, ReportColumn rc) throws Exception { String field_Id = rc.getFieldId(); String property_name = rc.getPropertyName(); String qualifier_name = rc.getQualifierName(); String source = rc.getSource(); String qualifier_value = rc.getQualifierValue(); String representational_form = rc.getRepresentationalForm(); // check: Boolean isPreferred = rc.getIsPreferred(); String property_type = rc.getPropertyType(); char delimiter_ch = rc.getDelimiter(); String delimiter = "" + delimiter_ch; //GF28844: delimiter = " " + delimiter + " "; if (isNull(field_Id)) field_Id = null; if (isNull(property_name)) property_name = null; if (isNull(qualifier_name)) qualifier_name = null; if (isNull(source)) source = null; if (isNull(qualifier_value)) qualifier_value = null; if (isNull(representational_form)) representational_form = null; if (isNull(property_type)) property_type = null; if (isNull(delimiter)) delimiter = null; String label = rc.getLabel().toUpperCase(); String assocName = SpecialCases.GetHasParent.getAssocName(field_Id); if (assocName != null && assocName.length() > 0) { Entity concept = SpecialCases.GetHasParent.getAssociatedConcept( definitionServices, uri, scheme, version, node, field_Id); if (concept != null) associated_concept = concept; else return ""; } if (SpecialCases.CDISC.ON) { String cdiscValue = SpecialCases.CDISC.getSubmissionValue(label, node, associated_concept, delimiter); if (cdiscValue != null) return cdiscValue; } if (field_Id.equals("Code")) return node.getEntityCode(); if (field_Id.contains("Associated Concept Code")) { if (associated_concept == null) return ""; return associated_concept.getEntityCode(); } Entity concept = node; if (property_name != null && property_name.compareTo("Contributing_Source") == 0) { concept = defining_root_concept; } else if (field_Id.indexOf("Associated") != -1) { if (associated_concept == null) return ""; concept = associated_concept; } else if (field_Id.indexOf("Parent") != -1) { if (_hierarchicalAssoName == null) { Vector<String> hierarchicalAssoName_vec = DataUtils.getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0) { return null; } _hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); } // Vector superconcept_vec = new DataUtils().getParentCodes(scheme, // version, node.getId()); Vector<String> superconcept_vec = DataUtils.getAssociationSourceCodes(scheme, version, node.getEntityCode(), _hierarchicalAssoName); if (superconcept_vec != null && superconcept_vec.size() > 0 && field_Id.indexOf("1st Parent") != -1) { String superconceptCode = (String) superconcept_vec .elementAt(superconcept_vec.size() - 1); if (field_Id.equals("1st Parent Code")) return superconceptCode; concept = DataUtils.getConceptByCode(scheme, version, null, superconceptCode); } else if (superconcept_vec != null && superconcept_vec.size() > 1 && field_Id.indexOf("2nd Parent") != -1) { String superconceptCode = (String) superconcept_vec .elementAt(superconcept_vec.size() - 2); if (field_Id.equals("2nd Parent Code")) return superconceptCode; concept = DataUtils.getConceptByCode(scheme, version, null, superconceptCode); } else { return " "; } } org.LexGrid.commonTypes.Property[] properties = new org.LexGrid.commonTypes.Property[] {}; if (property_type == null) { } else if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } String return_str = ""; // RWW change from space to empty string int num_matches = 0; if (field_Id.indexOf("Property Qualifier") != -1) { // getRepresentationalForm boolean match = false; boolean has_qualval = false; //GF28940 RWW for (int i = 0; i < properties.length && !has_qualval; i++) { //GF28940 RWW: there can only be one! //GF28940 RWW: commented //qualifier_value = null; org.LexGrid.commonTypes.Property p = properties[i]; if (p.getPropertyName().compareTo(property_name) == 0) // focus // on // matching // property { match = true; // <P90><![CDATA[<term-name>Black</term-name><term-group>PT</term-group><term-source>CDC</term-source><source-code>2056-0</source-code>]]></P90> if (source != null || representational_form != null || qualifier_name != null || isPreferred != null) { // compare isPreferred if (isPreferred != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; Boolean is_pref = presentation.getIsPreferred(); if (is_pref == null) { match = false; } else if (!is_pref.equals(isPreferred)) { match = false; } } // match representational_form if (match) { if (representational_form != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; if (presentation.getRepresentationalForm() .compareTo(representational_form) != 0) { match = false; } } } // match qualifier if (match) { if (qualifier_name != null) // match property // qualifier, if needed { boolean match_found = false; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if( qualifiers != null && qualifier_value != null ) { for (int j= 0; j < qualifiers.length; j++ ) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); //GF28940 RWW: there's no place in the model for another qualifier name //so I have to do this for "Property Qualifier" columns with a qualifier value //and luckily we don't have any using this! if( name.compareTo("subsource-name") == 0 && value.compareTo(qualifier_value) == 0 ) { has_qualval = true; } } } if (qualifiers != null && has_qualval ) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if (qualifier_name.compareTo(name) == 0) { match_found = true; qualifier_value = value; break; } } } if (!match_found) { match = false; } } } // match source if (match) { if (source != null) // match source { boolean match_found = false; Source[] sources = p.getSource(); for (int j = 0; j < sources.length; j++) { Source src = sources[j]; if (src.getContent().compareTo(source) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } } } if (match && qualifier_value != null) { num_matches++; if (num_matches == 1) { return_str = qualifier_value; } else { return_str = return_str + delimiter + qualifier_value; } } } return return_str; } else if (field_Id.compareToIgnoreCase("Property") == 0 || field_Id.contains("Associated Concept Property") || field_Id.indexOf("Parent Property") != -1) { for (int i = 0; i < properties.length; i++) { boolean match = false; org.LexGrid.commonTypes.Property p = properties[i]; String propertyName = p.getPropertyName(); if (propertyName.compareTo(property_name) == 0) // focus // on // matching // property { match = true; if (source != null || representational_form != null || qualifier_name != null || isPreferred != null) { // compare isPreferred if (isPreferred != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; Boolean is_pref = presentation.getIsPreferred(); if (is_pref == null) { match = false; } else if (is_pref != null && !is_pref.equals(isPreferred)) { match = false; } } // match representational_form if (match) { if (representational_form != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; String representationalForm = presentation.getRepresentationalForm(); if (representationalForm.compareTo(representational_form) != 0) { match = false; } } } // match qualifier if (match) { if (qualifier_name != null) // match property // qualifier, if needed { boolean match_found = false; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if (qualifier_name.compareTo(name) == 0 && qualifier_value.compareTo(value) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } // match source if (match) { if (source != null) // match source { boolean match_found = false; Source[] sources = p.getSource(); for (int j = 0; j < sources.length; j++) { Source src = sources[j]; if (src.getContent().compareTo(source) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } } } if (match) { num_matches++; if (num_matches == 1) { return_str = p.getValue().getContent(); } else { return_str = return_str + delimiter + p.getValue().getContent(); } } } } return return_str; } */ private boolean isNull(String s) { if (s == null) return true; s = s.trim(); if (s.length() == 0) return true; if (s.compareTo("") == 0) return true; if (s.compareToIgnoreCase("null") == 0) return true; return false; } // Code for supporting country code like report generation: private Vector<String> parseData(String line, String delimiter) { Vector<String> data_vec = new Vector<String>(); StringTokenizer st = new StringTokenizer(line, delimiter); while (st.hasMoreTokens()) { String value = st.nextToken(); data_vec.add(value); } return data_vec; } public Boolean generateSpecialReport(String outputDir, String standardReportLabel, String uid, StringBuffer warningMsg) { StandardReportTemplate standardReportTemplate = null; try { standardReportTemplate = getStandardReportTemplate( standardReportLabel, warningMsg); } catch (Exception e) { return warningMsg(warningMsg, "Unable to identify report label " + standardReportLabel + " -- report not generated."); } try { String queryString = standardReportTemplate.getRootConceptCode(); String delimiter = "|"; Vector<String> v = parseData(queryString, delimiter); String property = (String) v.elementAt(0); String source = (String) v.elementAt(1); String qualifier_name = (String) v.elementAt(2); String qualifier_value = (String) v.elementAt(3); String matchText = (String) v.elementAt(4); String matchAlgorithm = (String) v.elementAt(5); _logger.debug(StringUtils.SEPARATOR); _logger.debug("Method: generateSpecialReport"); _logger.debug(" * Output directory: " + outputDir); _logger.debug(" * standardReportLabel: " + standardReportLabel); _logger.debug(" * uid: " + uid); File dir = new File(outputDir); if (!dir.exists()) { _logger.debug("Output directory " + outputDir + " does not exist -- try to create the directory."); boolean retval = dir.mkdir(); if (!retval) { throw new Exception("Unable to create output directory " + outputDir + " -- please check privilege setting."); } else { _logger.debug("Output directory: " + outputDir + " created."); } } else { _logger.debug("Output directory: " + outputDir + " exists."); } String version = standardReportTemplate.getCodingSchemeVersion(); String pathname = outputDir + File.separator + standardReportLabel + "__" + version + ".txt"; pathname = pathname.replaceAll(" ", "_"); _logger.debug("Full path name: " + pathname); PrintWriter pw = openPrintWriter(pathname); if (pw == null) throw new Exception("Unable to create output file " + pathname + " -- please check privilege setting."); _logger.debug("opened PrintWriter " + pathname); int id = standardReportTemplate.getId(); String label = standardReportTemplate.getLabel(); String codingSchemeName = standardReportTemplate.getCodingSchemeName(); String codingSchemeVersion = standardReportTemplate.getCodingSchemeVersion(); String rootConceptCode = standardReportTemplate.getRootConceptCode(); String associationName = standardReportTemplate.getAssociationName(); boolean direction = standardReportTemplate.getDirection(); int level = standardReportTemplate.getLevel(); // char delim = '$'; // Character delimiter = standardReportTemplate.getDelimiter(); String delimeter_str = "\t"; _logger.debug(" * ID: " + id); _logger.debug(" * Label: " + label); _logger.debug(" * CodingSchemeName: " + codingSchemeName); _logger.debug(" * CodingSchemeVersion: " + codingSchemeVersion); _logger.debug(" * Root: " + rootConceptCode); _logger.debug(" * AssociationName: " + associationName); _logger.debug(" * Direction: " + direction); _logger.debug(" * Level: " + level); // _logger.debug("Delimiter: " + delimiter); Object[] objs = null; Collection<ReportColumn> cc = standardReportTemplate.getColumnCollection(); if (cc == null) { throw new Exception( "standardReportTemplate.getColumnCollection" + " returned null???"); } else { objs = cc.toArray(); } ReportColumn[] cols = null; if (cc != null) { cols = new ReportColumn[objs.length]; for (int i = 0; i < objs.length; i++) { gov.nih.nci.evs.reportwriter.bean.ReportColumn col = (gov.nih.nci.evs.reportwriter.bean.ReportColumn) objs[i]; Debug.print(col); cols[i] = col; } } _logger.debug(StringUtils.SEPARATOR); _logger.debug("* Start generating report..." + pathname); printReportHeading(pw, cols); // String scheme = standardReportTemplate.getCodingSchemeName(); version = standardReportTemplate.getCodingSchemeVersion(); Vector<String> property_vec = null; if (property != null && property.compareTo("null") != 0) { property_vec = new Vector<String>(); property_vec.add(property); } Vector<String> source_vec = null; if (source != null && source.compareTo("null") != 0) { source_vec = new Vector<String>(); source_vec.add(source); } Vector<String> qualifier_name_vec = null; if (qualifier_name != null && qualifier_name.compareTo("null") != 0) { qualifier_name_vec = new Vector<String>(); qualifier_name_vec.add(qualifier_name); } Vector<String> qualifier_value_vec = null; if (qualifier_value != null && qualifier_value.compareTo("null") != 0) { qualifier_value_vec = new Vector<String>(); qualifier_value_vec.add(qualifier_value); } int maxToReturn = 10000; String language = null; Vector<Entity> concept_vec = DataUtils.restrictToMatchingProperty(codingSchemeName, version, property_vec, source_vec, qualifier_name_vec, qualifier_value_vec, matchText, matchAlgorithm, language, maxToReturn); _logger.debug("concept_vec.size(): " + concept_vec.size()); String delim = "\t"; LexEVSValueSetDefinitionServices definitionServices = DataUtils.getValueSetDefinitionService(); String uri = DataUtils.codingSchemeName2URI(codingSchemeName, version); for (int i = 0; i < concept_vec.size(); i++) { Entity c = (Entity) concept_vec.elementAt(i); writeColumnData(definitionServices, uri, pw, codingSchemeName, version, null, null, c, delim, cols, true); } closePrintWriter(pw); _logger.debug("Generated output file: " + pathname); return createStandardReports(outputDir, standardReportLabel, uid, standardReportTemplate, pathname, version, delimeter_str); } catch (Exception e) { return warningMsg(warningMsg, ExceptionUtils.getStackTrace(e)); } } private String getPathname(String outputDir, String standardReportLabel, String version, String extension) { String pathname = outputDir + File.separator + standardReportLabel + "__" + version + extension; pathname = pathname.replaceAll(" ", "_"); _logger.debug("Full path name: " + pathname); return pathname; } public static enum ReportFormatType implements Comparator<ReportFormatType> { Text("Text (tab delimited)", 0), Excel("Microsoft Office Excel", 1), Html( "HyperText Markup Language", 2); private static HashMap<String, ReportFormatType> _map = new HashMap<String, ReportFormatType>(); private String _name = ""; private int _sortValue = -1; ReportFormatType(String name, int sortValue) { _name = name; _sortValue = sortValue; } public String getName() { return _name; } public int getSortValue() { return _sortValue; } public int compare(ReportFormatType obj1, ReportFormatType obj2) { int sortValue1 = obj1.getSortValue(); int sortValue2 = obj2.getSortValue(); if (sortValue1 == sortValue2) return obj1.getName().compareTo(obj2.getName()); return obj1.getSortValue() - obj2.getSortValue(); } public static ReportFormatType value_of(String name) { return _map.get(name); } static { for (ReportFormatType type : ReportFormatType.values()) { _map.put(type.getName(), type); } } } private Boolean createStandardReports(String textfile, String delimiter) throws Exception { AppProperties appProperties = AppProperties.getInstance(); String ncitUrl = appProperties.getProperty(AppProperties.NCIT_URL); String displayNCItCodeUrl = appProperties.getProperty(AppProperties.DISPLAY_NCIT_CODE_URL); AsciiToHtmlFormatter htmlFormatter = new AsciiToHtmlFormatter(); htmlFormatter.setDisplayNCItCodeUrl(displayNCItCodeUrl); FileFormatterBase[] formatters = new FileFormatterBase[] { new AsciiToExcelFormatter(), htmlFormatter }; Boolean bool_obj = true; for (FileFormatterBase formatter : formatters) { formatter.setNcitUrl(ncitUrl); formatter.setNcitCodeColumns(_ncitColumns); bool_obj &= formatter.convert(textfile, delimiter); } return bool_obj; } private Boolean createStandardReports(String outputDir, String standardReportLabel, String uid, StandardReportTemplate standardReportTemplate, String textfile, String version, String delimiter) throws Exception { Boolean bool_obj = createStandardReports(textfile, delimiter); String label = standardReportLabel + ".txt"; String pathname = textfile; String templateLabel = standardReportTemplate.getLabel(); String format = ReportFormatType.Text.getName(); String status = "DRAFT"; bool_obj &= StandardReportService.createStandardReport(label, textfile, templateLabel, format, status, uid); label = standardReportLabel + ".xls"; pathname = getPathname(outputDir, standardReportLabel, version, ".xls"); format = ReportFormatType.Excel.getName(); bool_obj &= StandardReportService.createStandardReport(label, pathname, templateLabel, format, status, uid); label = standardReportLabel + ".htm"; pathname = getPathname(outputDir, standardReportLabel, version, ".htm"); format = ReportFormatType.Html.getName(); bool_obj &= StandardReportService.createStandardReport(label, pathname, templateLabel, format, status, uid); return bool_obj; } public Entity getFocusConcept(String scheme, String version, Entity associated_concept, Entity node, String field_Id) { if (field_Id.indexOf("Associated Concept") != -1) { return associated_concept; } else if (field_Id.indexOf("Parent") != -1) { String associationName = DataUtils.getHasParentAssociationName(scheme, version, field_Id); if (associationName == null) { // find superconcept Vector superconcepts = DataUtils.getSuperconcepts(scheme, version, node.getEntityCode()); if (superconcepts == null) return null; if (superconcepts.size() == 0) return null; if (field_Id.startsWith("2nd")) { if (superconcepts.size() > 1) { return (Entity) superconcepts.elementAt(1); } else { return null; } } else { return (Entity) superconcepts.elementAt(0); } } else { // find associated concept based on associationName Vector<AssociatedConcept> asso_concepts = DataUtils.getRelatedConcepts(scheme, version, node.getEntityCode(), associationName, true); if (asso_concepts == null) { return null; } if (asso_concepts.size() == 0) { return null; } if (field_Id.startsWith("2nd")) { if (asso_concepts.size() > 1) { Entity e = (Entity) asso_concepts.elementAt(1).getReferencedEntry(); return e; } else { return null; } } else { Entity e = (Entity) asso_concepts.elementAt(0).getReferencedEntry(); return e; } } } return node; } public String getFocusConceptCode(Entity concept) { if (concept == null) return ""; return concept.getEntityCode(); } public static String getFocusConceptPropertyValue(Entity concept, String property_name, String property_type, String qualifier_name, String source, String qualifier_value, String representational_form, String delimiter, Boolean isPreferred) { if (concept == null) return ""; HashSet hset = new HashSet(); int num_matches = 0; org.LexGrid.commonTypes.Property[] properties = new org.LexGrid.commonTypes.Property[] {}; if (property_type == null) { } else if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } String return_str = ""; for (int i = 0; i < properties.length; i++) { boolean match = false; org.LexGrid.commonTypes.Property p = properties[i]; String propertyName = p.getPropertyName(); if (propertyName.compareTo(property_name) == 0) { match = true; if (source != null || representational_form != null || qualifier_name != null || isPreferred != null) { // compare isPreferred if (isPreferred != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; Boolean is_pref = presentation.getIsPreferred(); if (is_pref == null) { match = false; } else if (is_pref != null && !is_pref.equals(isPreferred)) { match = false; } } // match representational_form if (match) { if (representational_form != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; String representationalForm = presentation.getRepresentationalForm(); if (representationalForm.compareTo(representational_form) != 0) { match = false; } } } // match qualifier if (match) { if (qualifier_value != null) // match qualifier name vaue pair // qualifier, if needed { boolean match_found = false; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if (qualifier_name != null && qualifier_name.compareTo(name) == 0 && qualifier_value.compareTo(value) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } // match source if (match) { if (source != null) // match source { boolean match_found = false; Source[] sources = p.getSource(); for (int j = 0; j < sources.length; j++) { Source src = sources[j]; if (src.getContent().compareTo(source) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } } if (match) { String prop_value = p.getValue().getContent(); if (!hset.contains(prop_value)) { num_matches++; hset.add(prop_value); if (num_matches == 1) { return_str = prop_value; } else { return_str = return_str + delimiter + prop_value; } } } } } return return_str; } /* public String getFocusConceptPropertyQualifierValue( Entity concept, String property_name, String property_type, String qualifier_name, String source, String qualifier_value, String representational_form, String delimiter, Boolean isPreferred) { if (concept == null) return ""; int num_matches = 0; org.LexGrid.commonTypes.Property[] properties = new org.LexGrid.commonTypes.Property[] {}; if (property_type == null) { } else if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } String return_str = ""; // RWW change from space to empty string boolean match = false; boolean has_qualval = false; //GF28940 RWW for (int i = 0; i < properties.length && !has_qualval; i++) { //GF28940 RWW: there can only be one! //GF28940 RWW: commented //qualifier_value = null; org.LexGrid.commonTypes.Property p = properties[i]; if (p.getPropertyName().compareTo(property_name) == 0) { match = true; // <P90><![CDATA[<term-name>Black</term-name><term-group>PT</term-group><term-source>CDC</term-source><source-code>2056-0</source-code>]]></P90> if (source != null || representational_form != null || qualifier_name != null || isPreferred != null) { // compare isPreferred if (isPreferred != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; Boolean is_pref = presentation.getIsPreferred(); if (is_pref == null) { match = false; } else if (!is_pref.equals(isPreferred)) { match = false; } } // match representational_form if (match) { if (representational_form != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; if (presentation.getRepresentationalForm() .compareTo(representational_form) != 0) { match = false; } } } // match qualifier if (match) { if (qualifier_name != null) // match property // qualifier, if needed { boolean match_found = false; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if( qualifiers != null && qualifier_value != null ) { for (int j= 0; j < qualifiers.length; j++ ) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); //GF28940 RWW: there's no place in the model for another qualifier name //so I have to do this for "Property Qualifier" columns with a qualifier value //and luckily we don't have any using this! if( name.compareTo("subsource-name") == 0 && value.compareTo(qualifier_value) == 0 ) { has_qualval = true; } } } if (qualifiers != null && has_qualval ) { for (int j = 0; j < qualifiers.length; j++) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if (qualifier_name.compareTo(name) == 0) { match_found = true; qualifier_value = value; break; } } } if (!match_found) { match = false; } } } // match source if (match) { if (source != null) // match source { boolean match_found = false; Source[] sources = p.getSource(); for (int j = 0; j < sources.length; j++) { Source src = sources[j]; if (src.getContent().compareTo(source) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } } } if (match && qualifier_value != null) { num_matches++; if (num_matches == 1) { return_str = qualifier_value; } else { return_str = return_str + delimiter + qualifier_value; } } return return_str; } return ""; } */ public String getFocusConceptPropertyQualifierValue( Entity concept, String property_name, String property_type, String qualifier_name, String source, String qualifier_value, String representational_form, String delimiter, Boolean isPreferred) { /* // Business rule:: // If both qualifier name and qualifier value are present, then the source-code value would be returned for // the property that matched with the given pair of qualifier name and qualifier value. scheme = "NCI Thesaurus"; version = "11.04d"; code = "C3671"; FULL_SYN: INJURY RepresentationalForm: PT Source: FDA Qualifier name: source-code Qualifier value: 2348 Qualifier name: subsource-name Qualifier value: CDRH //C54027 FULL_SYN: PATIENT PROBLEM/MEDICAL PROBLEM RepresentationalForm: PT Source: FDA Qualifier name: source-code Qualifier value: 2688 Qualifier name: subsource-name Qualifier value: CDRH FULL_SYN: DEVICE ISSUE RepresentationalForm: PT Source: FDA Qualifier name: source-code Qualifier value: 2379 Qualifier name: subsource-name Qualifier value: CDRH */ if (concept == null) return ""; int num_matches = 0; org.LexGrid.commonTypes.Property[] properties = new org.LexGrid.commonTypes.Property[] {}; if (property_type == null) { } else if (property_type.compareToIgnoreCase("GENERIC") == 0) { properties = concept.getProperty(); } else if (property_type.compareToIgnoreCase("PRESENTATION") == 0) { properties = concept.getPresentation(); } else if (property_type.compareToIgnoreCase("COMMENT") == 0) { properties = concept.getComment(); } else if (property_type.compareToIgnoreCase("DEFINITION") == 0) { properties = concept.getDefinition(); } String return_str = ""; boolean match = false; String ret_qualifier_value = null; for (int i = 0; i < properties.length; i++) { ret_qualifier_value = null; org.LexGrid.commonTypes.Property p = properties[i]; if (p.getPropertyName().compareTo(property_name) == 0) { match = true; if (source != null || representational_form != null || qualifier_name != null || isPreferred != null) { // compare isPreferred if (isPreferred != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; Boolean is_pref = presentation.getIsPreferred(); if (is_pref == null) { match = false; } else if (!is_pref.equals(isPreferred)) { match = false; } } // match representational_form if (match) { if (representational_form != null && p instanceof Presentation) { Presentation presentation = (Presentation) p; if (presentation.getRepresentationalForm() .compareTo(representational_form) != 0) { match = false; } } } // match qualifier if (match) { if (qualifier_name != null) // match property { boolean match_found = false; PropertyQualifier[] qualifiers = p.getPropertyQualifier(); if (qualifiers != null && qualifiers.length > 0) { if (qualifier_value == null || qualifier_value.compareTo("") == 0) { // find qualifier value by matching qualifier name for (int j= 0; j < qualifiers.length; j++ ) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if( name.compareTo(qualifier_name) == 0) { ret_qualifier_value = value; match_found = true; break; } } } else { // qualifier value (subsource_name) is given for (int j= 0; j < qualifiers.length; j++ ) { PropertyQualifier q = qualifiers[j]; String name = q.getPropertyQualifierName(); String value = q.getValue().getContent(); if( name.compareTo(qualifier_name) == 0 && value.compareTo(qualifier_value) == 0) { for (int k= 0; k < qualifiers.length; k++ ) { q = qualifiers[k]; String q_name = q.getPropertyQualifierName(); String q_value = q.getValue().getContent(); if( q_name.compareTo("source-code") == 0) { ret_qualifier_value = q_value; match_found = true; break; } } } } } } if (!match_found) { match = false; } } } // match source if (match) { if (source != null) // match source { boolean match_found = false; Source[] sources = p.getSource(); for (int j = 0; j < sources.length; j++) { Source src = sources[j]; if (src.getContent().compareTo(source) == 0) { match_found = true; break; } } if (!match_found) { match = false; } } } } if (match && ret_qualifier_value != null) { num_matches++; if (num_matches == 1) { return_str = ret_qualifier_value; } else { return_str = return_str + delimiter + ret_qualifier_value; } } } } return return_str; } public String get_ReportColumnValue(LexEVSValueSetDefinitionServices definitionServices, String uri, String scheme, String version, Entity defining_root_concept, Entity associated_concept, Entity node, ReportColumn rc) throws Exception { String field_Id = rc.getFieldId(); if (field_Id.compareTo("Blank") == 0) { return ""; } if (field_Id.compareTo("Associated Concept Code") == 0 && associated_concept != null && node != null && associated_concept.getEntityCode().compareTo( node.getEntityCode() ) == 0) { return ""; } if (field_Id.compareTo("CDISC Submission Value") == 0) { return getCDISCSubmissionValue(scheme, version, associated_concept, node, rc); } Entity focused_concept = null; String property_name = rc.getPropertyName(); String qualifier_name = rc.getQualifierName(); String source = rc.getSource(); String qualifier_value = rc.getQualifierValue(); String representational_form = rc.getRepresentationalForm(); Boolean isPreferred = rc.getIsPreferred(); String property_type = rc.getPropertyType(); char delimiter_ch = rc.getDelimiter(); String delimiter = "" + delimiter_ch; //GF28844: delimiter = " " + delimiter + " "; if (isNull(field_Id)) field_Id = null; if (isNull(property_name)) property_name = null; if (property_name != null && property_name.compareTo("Extensible_List") == 0) { if (associated_concept != null && node != null && associated_concept.getEntityCode().compareTo( node.getEntityCode() ) != 0 ) return ""; } if (isNull(qualifier_name)) qualifier_name = null; if (isNull(source)) source = null; if (isNull(qualifier_value)) qualifier_value = null; if (isNull(representational_form)) representational_form = null; if (isNull(property_type)) property_type = null; if (isNull(delimiter)) delimiter = null; Entity concept = node; if (property_name != null && property_name.compareTo("Contributing_Source") == 0) { concept = defining_root_concept; } else { concept = getFocusConcept(scheme, version, associated_concept, node, field_Id); } if (field_Id.endsWith("Code")) { return getFocusConceptCode(concept); } else if (field_Id.endsWith("Property Qualifier")) { return getFocusConceptPropertyQualifierValue( concept, property_name, property_type, qualifier_name, source, qualifier_value, representational_form, delimiter, isPreferred); } else if (field_Id.endsWith("Property")) { return getFocusConceptPropertyValue( concept, property_name, property_type, qualifier_name, source, qualifier_value, representational_form, delimiter, isPreferred); } return null; } public String getCodeListPT(String code) { if (code == null) return null; if (_code2PTHashMap.containsKey(code)) { return (String) _code2PTHashMap.get(code); } return null; } public String getCDISCSubmissionValue(String scheme, String version, Entity associated_concept, Entity node, ReportColumn rc) { if (associated_concept == null || node == null) return null; String property_name = rc.getPropertyName(); String qualifier_name = rc.getQualifierName(); String source = rc.getSource(); String qualifier_value = rc.getQualifierValue(); String representational_form = rc.getRepresentationalForm(); Boolean isPreferred = rc.getIsPreferred(); String property_type = rc.getPropertyType(); char delimiter_ch = rc.getDelimiter(); String delimiter = "" + delimiter_ch; if (isNull(property_name)) property_name = null; if (isNull(qualifier_name)) qualifier_name = null; if (isNull(source)) source = null; if (isNull(qualifier_value)) qualifier_value = null; if (isNull(representational_form)) representational_form = null; if (isNull(property_type)) property_type = null; if (isNull(delimiter)) delimiter = null; String codeListPT = getCodeListPT(associated_concept.getEntityCode()); if (codeListPT == null) { codeListPT = getFocusConceptPropertyValue( associated_concept, "FULL_SYN", "PRESENTATION", null, "CDISC", null, "PT", delimiter, null); if (codeListPT != null) { _code2PTHashMap.put(associated_concept.getEntityCode(), codeListPT); } } if (codeListPT != null) { String source_code = "SDTM-" + codeListPT; qualifier_name = "source-code"; String retval = getFocusConceptPropertyValue( node, property_name, property_type, qualifier_name, source, source_code, representational_form, delimiter, isPreferred); if (retval != null && retval.compareTo("") != 0) return retval; } return getFocusConceptPropertyValue( node, property_name, property_type, null, source, null, representational_form, delimiter, isPreferred); //return DataUtils.getPTBySourceCode(scheme, version, node.getEntityCode(), source, source_code); } public void setReportColumns(ReportColumn[] cols) { for (int i = 0; i < cols.length; i++) { ReportColumn col = cols[i]; String field_id = col.getFieldId(); if (field_id.compareTo("CDISC Submission Value") == 0) { col.setFieldId("Property"); col.setRepresentationalForm("PT"); col.setSource("CDISC"); col.setQualifierName(null); col.setQualifierValue(null); } if (i == 1) { col.setFieldId("Blank"); } /* if (field_id.compareTo("Associated Concept Code") == 0) { col.setFieldId("Code"); } */ if (col.getPropertyName().compareTo("Extensible_List") == 0) { col.setFieldId("Property"); } } } public ReportColumn[] copyReportColumns(ReportColumn[] cols) { if (cols == null) return null; prev_subset_code = null; subheader_line_required = false; ReportColumn[] temporary_cols = new ReportColumn[cols.length]; for (int i = 0; i < cols.length; i++) { ReportColumn col = cols[i]; ReportColumn rc = new ReportColumn(); rc.setColumnNumber(col.getColumnNumber()); rc.setId(col.getId()); rc.setLabel(col.getLabel()); rc.setFieldId(col.getFieldId()); if (col.getFieldId().compareTo("CDISC Submission Value") == 0) { prev_subset_code = ""; subheader_line_required = true; } rc.setPropertyType(col.getPropertyType()); rc.setPropertyName(col.getPropertyName()); rc.setIsPreferred(col.getIsPreferred()); rc.setRepresentationalForm(col.getRepresentationalForm()); rc.setSource(col.getSource()); rc.setQualifierName(col.getQualifierName()); rc.setQualifierValue(col.getQualifierValue()); rc.setDelimiter(col.getDelimiter()); rc.setConditionalColumnId(col.getConditionalColumnId()); temporary_cols[i] = rc; } return temporary_cols; } }
package com.yahoo.container.di; import com.google.inject.Injector; import com.yahoo.config.ConfigInstance; import com.yahoo.config.ConfigurationRuntimeException; import com.yahoo.config.subscription.ConfigInterruptedException; import com.yahoo.container.BundlesConfig; import com.yahoo.container.ComponentsConfig; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.container.di.ConfigRetriever.BootstrapConfigs; import com.yahoo.container.di.ConfigRetriever.ConfigSnapshot; import com.yahoo.container.di.componentgraph.core.ComponentGraph; import com.yahoo.container.di.componentgraph.core.ComponentNode; import com.yahoo.container.di.componentgraph.core.JerseyNode; import com.yahoo.container.di.componentgraph.core.Node; import com.yahoo.container.di.config.RestApiContext; import com.yahoo.container.di.config.SubscriberFactory; import com.yahoo.vespa.config.ConfigKey; import org.osgi.framework.Bundle; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import static java.util.logging.Level.FINE; /** * @author gjoranv * @author Tony Vaagenes * @author ollivir */ public class Container { private static final Logger log = Logger.getLogger(Container.class.getName()); private final SubscriberFactory subscriberFactory; private ConfigKey<BundlesConfig> bundlesConfigKey; private ConfigKey<ComponentsConfig> componentsConfigKey; private final ComponentDeconstructor componentDeconstructor; private final Osgi osgi; private final ConfigRetriever configurer; private long previousConfigGeneration = -1L; private long leastGeneration = -1L; public Container(SubscriberFactory subscriberFactory, String configId, ComponentDeconstructor componentDeconstructor, Osgi osgi) { this.subscriberFactory = subscriberFactory; this.componentDeconstructor = componentDeconstructor; this.osgi = osgi; bundlesConfigKey = new ConfigKey<>(BundlesConfig.class, configId); componentsConfigKey = new ConfigKey<>(ComponentsConfig.class, configId); var bootstrapKeys = Set.of(bundlesConfigKey, componentsConfigKey); this.configurer = new ConfigRetriever(bootstrapKeys, subscriberFactory::getSubscriber); } public Container(SubscriberFactory subscriberFactory, String configId, ComponentDeconstructor componentDeconstructor) { this(subscriberFactory, configId, componentDeconstructor, new Osgi() { }); } public ComponentGraph getNewComponentGraph(ComponentGraph oldGraph, Injector fallbackInjector, boolean restartOnRedeploy) { try { Collection<Bundle> obsoleteBundles = new HashSet<>(); ComponentGraph newGraph = getConfigAndCreateGraph(oldGraph, fallbackInjector, restartOnRedeploy, obsoleteBundles); newGraph.reuseNodes(oldGraph); constructComponents(newGraph); deconstructObsoleteComponents(oldGraph, newGraph, obsoleteBundles); return newGraph; } catch (Throwable t) { // TODO: Wrap ComponentConstructorException in an Error when generation==0 (+ unit test that Error is thrown) invalidateGeneration(oldGraph.generation(), t); throw t; } } private ComponentGraph getConfigAndCreateGraph(ComponentGraph graph, Injector fallbackInjector, boolean restartOnRedeploy, Collection<Bundle> obsoleteBundles) // NOTE: Return value { ConfigSnapshot snapshot; while (true) { snapshot = configurer.getConfigs(graph.configKeys(), leastGeneration, restartOnRedeploy); log.log(FINE, String.format("createNewGraph:\n" + "graph.configKeys = %s\n" + "graph.generation = %s\n" + "snapshot = %s\n", graph.configKeys(), graph.generation(), snapshot)); if (snapshot instanceof BootstrapConfigs) { if (getBootstrapGeneration() <= previousConfigGeneration) { throw new IllegalStateException(String.format( "Got bootstrap configs out of sequence for old config generation %d.\n" + "Previous config generation is %d", getBootstrapGeneration(), previousConfigGeneration)); } log.log(FINE, String.format( "Got new bootstrap generation\n" + "bootstrap generation = %d\n" + "components generation: %d\n" + "previous generation: %d\n", getBootstrapGeneration(), getComponentsGeneration(), previousConfigGeneration)); Collection<Bundle> bundlesToRemove = installBundles(snapshot.configs()); obsoleteBundles.addAll(bundlesToRemove); graph = createComponentsGraph(snapshot.configs(), getBootstrapGeneration(), fallbackInjector); // Continues loop } else if (snapshot instanceof ConfigRetriever.ComponentsConfigs) { break; } } log.log(FINE, String.format( "Got components configs,\n" + "bootstrap generation = %d\n" + "components generation: %d\n" + "previous generation: %d", getBootstrapGeneration(), getComponentsGeneration(), previousConfigGeneration)); return createAndConfigureComponentsGraph(snapshot.configs(), fallbackInjector); } private long getBootstrapGeneration() { return configurer.getBootstrapGeneration(); } private long getComponentsGeneration() { return configurer.getComponentsGeneration(); } private ComponentGraph createAndConfigureComponentsGraph(Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> componentsConfigs, Injector fallbackInjector) { ComponentGraph componentGraph = createComponentsGraph(componentsConfigs, getComponentsGeneration(), fallbackInjector); componentGraph.setAvailableConfigs(componentsConfigs); return componentGraph; } private void constructComponents(ComponentGraph graph) { graph.nodes().forEach(Node::constructInstance); } private void deconstructObsoleteComponents(ComponentGraph oldGraph, ComponentGraph newGraph, Collection<Bundle> obsoleteBundles) { IdentityHashMap<Object, Object> oldComponents = new IdentityHashMap<>(); oldGraph.allConstructedComponentsAndProviders().forEach(c -> oldComponents.put(c, null)); newGraph.allConstructedComponentsAndProviders().forEach(oldComponents::remove); componentDeconstructor.deconstruct(oldComponents.keySet(), obsoleteBundles); } private Set<Bundle> installBundles(Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> configsIncludingBootstrapConfigs) { BundlesConfig bundlesConfig = getConfig(bundlesConfigKey, configsIncludingBootstrapConfigs); return osgi.useBundles(bundlesConfig.bundle()); } private ComponentGraph createComponentsGraph(Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> configsIncludingBootstrapConfigs, long generation, Injector fallbackInjector) { previousConfigGeneration = generation; ComponentGraph graph = new ComponentGraph(generation); ComponentsConfig componentsConfig = getConfig(componentsConfigKey, configsIncludingBootstrapConfigs); if (componentsConfig == null) { throw new ConfigurationRuntimeException("The set of all configs does not include a valid 'components' config. Config set: " + configsIncludingBootstrapConfigs.keySet()); } addNodes(componentsConfig, graph); injectNodes(componentsConfig, graph); graph.complete(fallbackInjector); return graph; } private void addNodes(ComponentsConfig componentsConfig, ComponentGraph graph) { for (ComponentsConfig.Components config : componentsConfig.components()) { BundleInstantiationSpecification specification = bundleInstantiationSpecification(config); Class<?> componentClass = osgi.resolveClass(specification); Node componentNode; if (RestApiContext.class.isAssignableFrom(componentClass)) { Class<? extends RestApiContext> nodeClass = componentClass.asSubclass(RestApiContext.class); componentNode = new JerseyNode(specification.id, config.configId(), nodeClass, osgi); } else { componentNode = new ComponentNode(specification.id, config.configId(), componentClass, null); } graph.add(componentNode); } } private void injectNodes(ComponentsConfig config, ComponentGraph graph) { for (ComponentsConfig.Components component : config.components()) { Node componentNode = ComponentGraph.getNode(graph, component.id()); for (ComponentsConfig.Components.Inject inject : component.inject()) { //TODO: Support inject.name() componentNode.inject(ComponentGraph.getNode(graph, inject.id())); } } } private void invalidateGeneration(long generation, Throwable cause) { leastGeneration = Math.max(configurer.getComponentsGeneration(), configurer.getBootstrapGeneration()) + 1; if (!(cause instanceof InterruptedException) && !(cause instanceof ConfigInterruptedException)) { log.log(Level.WARNING, newGraphErrorMessage(generation, cause), cause); } } private static String newGraphErrorMessage(long generation, Throwable cause) { String failedFirstMessage = "Failed to set up first component graph"; String failedNewMessage = "Failed to set up new component graph"; String constructMessage = " due to error when constructing one of the components"; String retainMessage = ". Retaining previous component generation."; if (generation == 0) { if (cause instanceof ComponentNode.ComponentConstructorException) { return failedFirstMessage + constructMessage; } else { return failedFirstMessage; } } else { if (cause instanceof ComponentNode.ComponentConstructorException) { return failedNewMessage + constructMessage + retainMessage; } else { return failedNewMessage + retainMessage; } } } public void shutdown(ComponentGraph graph, ComponentDeconstructor deconstructor) { shutdownConfigurer(); if (graph != null) { deconstructAllComponents(graph, deconstructor); } } void shutdownConfigurer() { configurer.shutdown(); } // Reload config manually, when subscribing to non-configserver sources public void reloadConfig(long generation) { subscriberFactory.reloadActiveSubscribers(generation); } private void deconstructAllComponents(ComponentGraph graph, ComponentDeconstructor deconstructor) { // This is only used for shutdown, so no need to uninstall any bundles. deconstructor.deconstruct(graph.allConstructedComponentsAndProviders(), Collections.emptyList()); } public static <T extends ConfigInstance> T getConfig(ConfigKey<T> key, Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> configs) { ConfigInstance inst = configs.get(key); if (inst == null || key.getConfigClass() == null) { throw new RuntimeException("Missing config " + key); } return key.getConfigClass().cast(inst); } private static BundleInstantiationSpecification bundleInstantiationSpecification(ComponentsConfig.Components config) { return BundleInstantiationSpecification.getFromStrings(config.id(), config.classId(), config.bundle()); } }
// LegacyPlugin.java package imagej.legacy.plugin; import ij.IJ; import ij.ImagePlus; import imagej.ImageJ; import imagej.data.Dataset; import imagej.legacy.DatasetHarmonizer; import imagej.legacy.LegacyImageMap; import imagej.legacy.LegacyManager; import imagej.plugin.ImageJPlugin; import imagej.plugin.Parameter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Executes an IJ1 plugin. * * @author Curtis Rueden * @author Barry DeZonia */ public class LegacyPlugin implements ImageJPlugin { @Parameter private String className; @Parameter private String arg; @Parameter(output=true) private List<Dataset> outputs; /** Used to provide one list of datasets per calling thread. */ private static ThreadLocal<Set<ImagePlus>> outputImps = new ThreadLocal<Set<ImagePlus>>() { @Override protected synchronized Set<ImagePlus> initialValue() { return new HashSet<ImagePlus>(); } }; // -- public interface -- @Override public void run() { /* use current imp as input to harmonize : no a) harmonize all ds (from Obj man) b) set imp of active ds as current image set temp curr im or set curr image dirty flag for a ds 1 for harm and 1 for saved image map can track dirty harm and listen events ds can track dirty saved */ final LegacyImageMap map = ImageJ.get(LegacyManager.class).getImageMap(); final DatasetHarmonizer harmonizer = new DatasetHarmonizer(map.getTranslator()); final Set<ImagePlus> outputSet = LegacyPlugin.getOutputs(); outputSet.clear(); harmonizeInputs(map, harmonizer); // set current temp image or curr image IJ.runPlugIn(className, arg); harmonizeCurrentImagePlus(map, harmonizer); outputs = harmonizeOutputs(map, harmonizer); outputSet.clear(); } /** * Gets a list for storing output parameter values. * This method is thread-safe, because it uses a separate map per thread. */ public static Set<ImagePlus> getOutputs() { return outputImps.get(); } // -- helpers -- private void harmonizeInputs(LegacyImageMap map, DatasetHarmonizer harmonizer) { } private void harmonizeCurrentImagePlus(LegacyImageMap map, DatasetHarmonizer harmonizer) { // this plugin may not have any outputs but just changes current ImagePlus // make sure we catch any changes via harmonization ImagePlus currImp = IJ.getImage(); Dataset ds = map.findDataset(currImp); if (ds != null) harmonizer.harmonize(ds, currImp); } private List<Dataset> harmonizeOutputs(LegacyImageMap map, DatasetHarmonizer harmonizer) { List<Dataset> datasets = new ArrayList<Dataset>(); // also harmonize all outputs for (ImagePlus imp : getOutputs()) { Dataset ds = map.findDataset(imp); if (ds == null) ds = map.registerLegacyImage(imp); else harmonizer.harmonize(ds, imp); datasets.add(ds); } return datasets; } }
package de.danoeh.antennapod.core.feed; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.Nullable; import android.text.TextUtils; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import de.danoeh.antennapod.core.preferences.PlaybackPreferences; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.storage.DBWriter; import de.danoeh.antennapod.core.storage.PodDBAdapter; import de.danoeh.antennapod.core.util.ChapterUtils; import de.danoeh.antennapod.core.util.playback.Playable; public class FeedMedia extends FeedFile implements Playable { private static final String TAG = "FeedMedia"; public static final int FEEDFILETYPE_FEEDMEDIA = 2; public static final int PLAYABLE_TYPE_FEEDMEDIA = 1; public static final String PREF_MEDIA_ID = "FeedMedia.PrefMediaId"; public static final String PREF_FEED_ID = "FeedMedia.PrefFeedId"; /** * Indicates we've checked on the size of the item via the network * and got an invalid response. Using Integer.MIN_VALUE because * 1) we'll still check on it in case it gets downloaded (it's <= 0) * 2) By default all FeedMedia have a size of 0 if we don't know it, * so this won't conflict with existing practice. */ private static final int CHECKED_ON_SIZE_BUT_UNKNOWN = Integer.MIN_VALUE; private int duration; private int position; // Current position in file private long lastPlayedTime; // Last time this media was played (in ms) private int played_duration; // How many ms of this file have been played (for autoflattring) private long size; // File size in Byte private String mime_type; @Nullable private volatile FeedItem item; private Date playbackCompletionDate; // if null: unknown, will be checked private Boolean hasEmbeddedPicture; /* Used for loading item when restoring from parcel. */ private long itemID; public FeedMedia(FeedItem i, String download_url, long size, String mime_type) { super(null, download_url, false); this.item = i; this.size = size; this.mime_type = mime_type; } public FeedMedia(long id, FeedItem item, int duration, int position, long size, String mime_type, String file_url, String download_url, boolean downloaded, Date playbackCompletionDate, int played_duration, long lastPlayedTime) { super(file_url, download_url, downloaded); this.id = id; this.item = item; this.duration = duration; this.position = position; this.played_duration = played_duration; this.size = size; this.mime_type = mime_type; this.playbackCompletionDate = playbackCompletionDate == null ? null : (Date) playbackCompletionDate.clone(); this.lastPlayedTime = lastPlayedTime; } public FeedMedia(long id, FeedItem item, int duration, int position, long size, String mime_type, String file_url, String download_url, boolean downloaded, Date playbackCompletionDate, int played_duration, Boolean hasEmbeddedPicture, long lastPlayedTime) { this(id, item, duration, position, size, mime_type, file_url, download_url, downloaded, playbackCompletionDate, played_duration, lastPlayedTime); this.hasEmbeddedPicture = hasEmbeddedPicture; } public static FeedMedia fromCursor(Cursor cursor) { int indexId = cursor.getColumnIndex(PodDBAdapter.KEY_ID); int indexPlaybackCompletionDate = cursor.getColumnIndex(PodDBAdapter.KEY_PLAYBACK_COMPLETION_DATE); int indexDuration = cursor.getColumnIndex(PodDBAdapter.KEY_DURATION); int indexPosition = cursor.getColumnIndex(PodDBAdapter.KEY_POSITION); int indexSize = cursor.getColumnIndex(PodDBAdapter.KEY_SIZE); int indexMimeType = cursor.getColumnIndex(PodDBAdapter.KEY_MIME_TYPE); int indexFileUrl = cursor.getColumnIndex(PodDBAdapter.KEY_FILE_URL); int indexDownloadUrl = cursor.getColumnIndex(PodDBAdapter.KEY_DOWNLOAD_URL); int indexDownloaded = cursor.getColumnIndex(PodDBAdapter.KEY_DOWNLOADED); int indexPlayedDuration = cursor.getColumnIndex(PodDBAdapter.KEY_PLAYED_DURATION); int indexLastPlayedTime = cursor.getColumnIndex(PodDBAdapter.KEY_LAST_PLAYED_TIME); long mediaId = cursor.getLong(indexId); Date playbackCompletionDate = null; long playbackCompletionTime = cursor.getLong(indexPlaybackCompletionDate); if (playbackCompletionTime > 0) { playbackCompletionDate = new Date(playbackCompletionTime); } Boolean hasEmbeddedPicture; switch(cursor.getInt(cursor.getColumnIndex(PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE))) { case 1: hasEmbeddedPicture = Boolean.TRUE; break; case 0: hasEmbeddedPicture = Boolean.FALSE; break; default: hasEmbeddedPicture = null; break; } return new FeedMedia( mediaId, null, cursor.getInt(indexDuration), cursor.getInt(indexPosition), cursor.getLong(indexSize), cursor.getString(indexMimeType), cursor.getString(indexFileUrl), cursor.getString(indexDownloadUrl), cursor.getInt(indexDownloaded) > 0, playbackCompletionDate, cursor.getInt(indexPlayedDuration), hasEmbeddedPicture, cursor.getLong(indexLastPlayedTime) ); } @Override public String getHumanReadableIdentifier() { if (item != null && item.getTitle() != null) { return item.getTitle(); } else { return download_url; } } /** * Uses mimetype to determine the type of media. */ public MediaType getMediaType() { if (mime_type == null || mime_type.isEmpty()) { return MediaType.UNKNOWN; } else { if (mime_type.startsWith("audio")) { return MediaType.AUDIO; } else if (mime_type.startsWith("video")) { return MediaType.VIDEO; } else if (mime_type.equals("application/ogg")) { return MediaType.AUDIO; } } return MediaType.UNKNOWN; } public void updateFromOther(FeedMedia other) { // reset to new if feed item did link to a file before if(TextUtils.isEmpty(download_url) && !TextUtils.isEmpty(other.download_url)) { item.setNew(); } super.updateFromOther(other); if (other.size > 0) { size = other.size; } if (other.mime_type != null) { mime_type = other.mime_type; } } public boolean compareWithOther(FeedMedia other) { if (super.compareWithOther(other)) { return true; } if (other.mime_type != null) { if (mime_type == null || !mime_type.equals(other.mime_type)) { return true; } } if (other.size > 0 && other.size != size) { return true; } return false; } /** * Reads playback preferences to determine whether this FeedMedia object is * currently being played. */ public boolean isPlaying() { return PlaybackPreferences.getCurrentlyPlayingMedia() == FeedMedia.PLAYABLE_TYPE_FEEDMEDIA && PlaybackPreferences.getCurrentlyPlayingFeedMediaId() == id; } /** * Reads playback preferences to determine whether this FeedMedia object is * currently being played and the current player status is playing. */ public boolean isCurrentlyPlaying() { return isPlaying() && ((PlaybackPreferences.getCurrentPlayerStatus() == PlaybackPreferences.PLAYER_STATUS_PLAYING)); } /** * Reads playback preferences to determine whether this FeedMedia object is * currently being played and the current player status is paused. */ public boolean isCurrentlyPaused() { return isPlaying() && ((PlaybackPreferences.getCurrentPlayerStatus() == PlaybackPreferences.PLAYER_STATUS_PAUSED)); } public boolean hasAlmostEnded() { int smartMarkAsPlayedSecs = UserPreferences.getSmartMarkAsPlayedSecs(); return this.position >= this.duration - smartMarkAsPlayedSecs * 1000; } @Override public int getTypeAsInt() { return FEEDFILETYPE_FEEDMEDIA; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } @Override public void setLastPlayedTime(long lastPlayedTime) { this.lastPlayedTime = lastPlayedTime; } public int getPlayedDuration() { return played_duration; } public void setPlayedDuration(int played_duration) { this.played_duration = played_duration; } public int getPosition() { return position; } @Override public long getLastPlayedTime() { return lastPlayedTime; } public void setPosition(int position) { this.position = position; if(position > 0 && item != null && item.isNew()) { this.item.setPlayed(false); } } public long getSize() { return size; } public void setSize(long size) { this.size = size; } /** * Indicates we asked the service what the size was, but didn't * get a valid answer and we shoudln't check using the network again. */ public void setCheckedOnSizeButUnknown() { this.size = CHECKED_ON_SIZE_BUT_UNKNOWN; } public boolean checkedOnSizeButUnknown() { return (CHECKED_ON_SIZE_BUT_UNKNOWN == this.size); } public String getMime_type() { return mime_type; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } @Nullable public FeedItem getItem() { return item; } /** * Sets the item object of this FeedMedia. If the given * FeedItem object is not null, it's 'media'-attribute value * will also be set to this media object. */ public void setItem(FeedItem item) { this.item = item; if (item != null && item.getMedia() != this) { item.setMedia(this); } } public Date getPlaybackCompletionDate() { return playbackCompletionDate == null ? null : (Date) playbackCompletionDate.clone(); } public void setPlaybackCompletionDate(Date playbackCompletionDate) { this.playbackCompletionDate = playbackCompletionDate == null ? null : (Date) playbackCompletionDate.clone(); } public boolean isInProgress() { return (this.position > 0); } @Override public int describeContents() { return 0; } public boolean hasEmbeddedPicture() { return false; // TODO: reenable! //if(hasEmbeddedPicture == null) { // checkEmbeddedPicture(); //return hasEmbeddedPicture; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeLong(item != null ? item.getId() : 0L); dest.writeInt(duration); dest.writeInt(position); dest.writeLong(size); dest.writeString(mime_type); dest.writeString(file_url); dest.writeString(download_url); dest.writeByte((byte) ((downloaded) ? 1 : 0)); dest.writeLong((playbackCompletionDate != null) ? playbackCompletionDate.getTime() : 0); dest.writeInt(played_duration); dest.writeLong(lastPlayedTime); } @Override public void writeToPreferences(Editor prefEditor) { if(item != null && item.getFeed() != null) { prefEditor.putLong(PREF_FEED_ID, item.getFeed().getId()); } else { prefEditor.putLong(PREF_FEED_ID, 0L); } prefEditor.putLong(PREF_MEDIA_ID, id); } @Override public void loadMetadata() throws PlayableException { if (item == null && itemID != 0) { item = DBReader.getFeedItem(itemID); } } @Override public void loadChapterMarks() { if (item == null && itemID != 0) { item = DBReader.getFeedItem(itemID); } // check if chapters are stored in db and not loaded yet. if (item != null && item.hasChapters() && item.getChapters() == null) { DBReader.loadChaptersOfFeedItem(item); } else if (item != null && item.getChapters() == null && !localFileAvailable()) { ChapterUtils.loadChaptersFromStreamUrl(this); if (getChapters() != null && item != null) { DBWriter.setFeedItem( item); } } } @Override public String getEpisodeTitle() { if (item == null) { return null; } if (getItem().getTitle() != null) { return getItem().getTitle(); } else { return getItem().getIdentifyingValue(); } } @Override public List<Chapter> getChapters() { if (item == null) { return null; } return getItem().getChapters(); } @Override public String getWebsiteLink() { if (item == null) { return null; } return getItem().getLink(); } @Override public String getFeedTitle() { if (item == null) { return null; } return getItem().getFeed().getTitle(); } @Override public Object getIdentifier() { return id; } @Override public String getLocalMediaUrl() { return file_url; } @Override public String getStreamUrl() { return download_url; } @Override public String getPaymentLink() { if (item == null) { return null; } return getItem().getPaymentLink(); } @Override public boolean localFileAvailable() { return isDownloaded() && file_url != null; } @Override public boolean streamAvailable() { return download_url != null; } @Override public void saveCurrentPosition(SharedPreferences pref, int newPosition, long timeStamp) { if(item != null && item.isNew()) { DBWriter.markItemPlayed(FeedItem.UNPLAYED, item.getId()); } setPosition(newPosition); setLastPlayedTime(timeStamp); DBWriter.setFeedMediaPlaybackInformation(this); } @Override public void onPlaybackStart() { } @Override public void onPlaybackCompleted() { } @Override public int getPlayableType() { return PLAYABLE_TYPE_FEEDMEDIA; } @Override public void setChapters(List<Chapter> chapters) { getItem().setChapters(chapters); } @Override public Callable<String> loadShownotes() { return new Callable<String>() { @Override public String call() throws Exception { if (item == null) { item = DBReader.getFeedItem( itemID); } if (item.getContentEncoded() == null || item.getDescription() == null) { DBReader.loadExtraInformationOfFeedItem( item); } return (item.getContentEncoded() != null) ? item.getContentEncoded() : item.getDescription(); } }; } public static final Parcelable.Creator<FeedMedia> CREATOR = new Parcelable.Creator<FeedMedia>() { public FeedMedia createFromParcel(Parcel in) { final long id = in.readLong(); final long itemID = in.readLong(); FeedMedia result = new FeedMedia(id, null, in.readInt(), in.readInt(), in.readLong(), in.readString(), in.readString(), in.readString(), in.readByte() != 0, new Date(in.readLong()), in.readInt(), in.readLong()); result.itemID = itemID; return result; } public FeedMedia[] newArray(int size) { return new FeedMedia[size]; } }; @Override public Uri getImageUri() { if (hasEmbeddedPicture()) { Uri.Builder builder = new Uri.Builder(); builder.scheme(SCHEME_MEDIA).encodedPath(getLocalMediaUrl()); if (item != null && item.getFeed() != null) { final Uri feedImgUri = item.getFeed().getImageUri(); if (feedImgUri != null) { builder.appendQueryParameter(PARAM_FALLBACK, feedImgUri.toString()); } } return builder.build(); } else if(item != null) { return item.getImageUri(); } else { return null; } } public void setHasEmbeddedPicture(Boolean hasEmbeddedPicture) { this.hasEmbeddedPicture = hasEmbeddedPicture; } @Override public void setDownloaded(boolean downloaded) { super.setDownloaded(downloaded); if(item != null && downloaded) { item.setPlayed(false); } } @Override public void setFile_url(String file_url) { super.setFile_url(file_url); } private void checkEmbeddedPicture() { if (!localFileAvailable()) { hasEmbeddedPicture = Boolean.FALSE; return; } MediaMetadataRetriever mmr = new MediaMetadataRetriever(); try { mmr.setDataSource(getLocalMediaUrl()); byte[] image = mmr.getEmbeddedPicture(); if(image != null) { hasEmbeddedPicture = Boolean.TRUE; } else { hasEmbeddedPicture = Boolean.FALSE; } } catch (Exception e) { e.printStackTrace(); hasEmbeddedPicture = Boolean.FALSE; } } }
package hudson.slaves; import hudson.Functions; import hudson.model.Descriptor; import hudson.model.TaskListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Convenient base implementation of {@link ComputerLauncher} that allows * subtypes to perform some initialization (typically something cloud/v12n related * to power up the machine), then to delegate to another {@link ComputerLauncher} * to connect. * * @author Kohsuke Kawaguchi * @since 1.382 */ public abstract class DelegatingComputerLauncher extends ComputerLauncher { protected ComputerLauncher launcher; protected DelegatingComputerLauncher(ComputerLauncher launcher) { this.launcher = launcher; } public ComputerLauncher getLauncher() { return launcher; } @Override public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException { getLauncher().launch(computer, listener); } @Override public void afterDisconnect(SlaveComputer computer, TaskListener listener) { getLauncher().afterDisconnect(computer, listener); } @Override public void beforeDisconnect(SlaveComputer computer, TaskListener listener) { getLauncher().beforeDisconnect(computer, listener); } public static abstract class DescriptorImpl extends Descriptor<ComputerLauncher> { /** * Returns the applicable nested computer launcher types. * The default implementation avoids all delegating descriptors, as that creates infinite recursion. */ public List<Descriptor<ComputerLauncher>> getApplicableDescriptors() { List<Descriptor<ComputerLauncher>> r = new ArrayList<Descriptor<ComputerLauncher>>(); for (Descriptor<ComputerLauncher> d : Functions.getComputerLauncherDescriptors()) { if (DelegatingComputerLauncher.class.isInstance(d)) continue; r.add(d); } return r; } } }
package org.mskcc.cbio.portal.dao; import org.mskcc.cbio.portal.model.CancerStudy; import org.mskcc.cbio.portal.model.TypeOfCancer; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; /** * Analogous to and replaces the old DaoCancerType. A CancerStudy has a NAME and * DESCRIPTION. If PUBLIC is true a CancerStudy can be accessed by anyone, * otherwise can only be accessed through access control. * * @author Ethan Cerami * @author Arthur Goldberg goldberg@cbio.mskcc.org */ public final class DaoCancerStudy { private DaoCancerStudy() {} private static final Map<String,CancerStudy> byStableId = new HashMap<String,CancerStudy>(); private static final Map<Integer,CancerStudy> byInternalId = new HashMap<Integer,CancerStudy>(); static { reCache(); } private static synchronized void reCache() { byStableId.clear(); byInternalId.clear(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoCancerStudy.class); pstmt = con.prepareStatement("SELECT * FROM cancer_study"); rs = pstmt.executeQuery(); while (rs.next()) { CancerStudy cancerStudy = extractCancerStudy(rs); cacheCancerStudy(cancerStudy); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtil.closeAll(DaoCancerStudy.class, con, pstmt, rs); } } private static void cacheCancerStudy(CancerStudy study) { byStableId.put(study.getCancerStudyStableId(), study); byInternalId.put(study.getInternalId(), study); } /** * Adds a cancer study to the Database. * Updates cancerStudy with its auto incremented uid, in studyID. * * @param cancerStudy Cancer Study Object. * @throws DaoException Database Error. */ public static void addCancerStudy(CancerStudy cancerStudy) throws DaoException { addCancerStudy(cancerStudy, false); } /** * Adds a cancer study to the Database. * @param cancerStudy * @param overwrite if true, overwrite if exist. * @throws DaoException */ public static void addCancerStudy(CancerStudy cancerStudy, boolean overwrite) throws DaoException { // make sure that cancerStudy refers to a valid TypeOfCancerId // TODO: have a foreign key constraint do this; why not? TypeOfCancer aTypeOfCancer = DaoTypeOfCancer.getTypeOfCancerById (cancerStudy.getTypeOfCancerId()); if (null == aTypeOfCancer) { throw new DaoException("cancerStudy.getTypeOfCancerId() '" + cancerStudy.getTypeOfCancerId() + "' does not refer to a TypeOfCancer."); } // CANCER_STUDY_IDENTIFIER cannot be null String stableId = cancerStudy.getCancerStudyStableId(); if (stableId == null) { throw new DaoException("Cancer study stable ID cannot be null."); } CancerStudy existing = getCancerStudyByStableId(stableId); if (existing!=null) { if (overwrite) { System.out.println("Overwrite cancer study " + stableId); deleteCancerStudy(existing.getInternalId()); } else { throw new DaoException("Cancer study " + stableId + "is already imported."); } } Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoCancerStudy.class); pstmt = con.prepareStatement("INSERT INTO cancer_study " + "( `CANCER_STUDY_IDENTIFIER`, `NAME`, " + "`DESCRIPTION`, `PUBLIC`, `TYPE_OF_CANCER_ID`, " + "`PMID`, `CITATION`, `GROUPS` ) VALUES (?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, stableId); pstmt.setString(2, cancerStudy.getName()); pstmt.setString(3, cancerStudy.getDescription()); pstmt.setBoolean(4, cancerStudy.isPublicStudy()); pstmt.setString(5, cancerStudy.getTypeOfCancerId()); pstmt.setString(6, cancerStudy.getPmid()); pstmt.setString(7, cancerStudy.getCitation()); Set<String> groups = cancerStudy.getGroups(); if (groups==null) { pstmt.setString(8, null); } else { pstmt.setString(8, StringUtils.join(groups, ";")); } pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { int autoId = rs.getInt(1); cancerStudy.setInternalId(autoId); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoCancerStudy.class, con, pstmt, rs); } reCache(); } /** * Return the cancerStudy identified by the internal cancer study ID, if it exists. * * @param cancerStudyID Internal (int) Cancer Study ID. * @return Cancer Study Object, or null if there's no such study. */ public static CancerStudy getCancerStudyByInternalId(int cancerStudyID) { return byInternalId.get(cancerStudyID); } /** * Returns the cancerStudy identified by the stable identifier, if it exists. * * @param cancerStudyStableId Cancer Study Stable ID. * @return the CancerStudy, or null if there's no such study. */ public static CancerStudy getCancerStudyByStableId(String cancerStudyStableId) { return byStableId.get(cancerStudyStableId); } /** * Indicates whether the cancerStudy identified by the stable ID exists. * * @param cancerStudyStableId Cancer Study Stable ID. * @return true if the CancerStudy exists, otherwise false */ public static boolean doesCancerStudyExistByStableId(String cancerStudyStableId) { return byStableId.containsKey(cancerStudyStableId); } /** * Indicates whether the cancerStudy identified by internal study ID exist. * does no access control, so only returns a boolean. * * @param internalCancerStudyId Internal Cancer Study ID. * @return true if the CancerStudy exists, otherwise false */ public static boolean doesCancerStudyExistByInternalId(int internalCancerStudyId) { return byInternalId.containsKey(internalCancerStudyId); } /** * Returns all the cancerStudies. * * @return ArrayList of all CancerStudy Objects. */ public static ArrayList<CancerStudy> getAllCancerStudies() { return new ArrayList<CancerStudy>(byStableId.values()); } /** * Gets Number of Cancer Studies. * @return number of cancer studies. */ public static int getCount() { return byStableId.size(); } /** * Deletes all Cancer Studies. * @throws DaoException Database Error. */ public static void deleteAllRecords() throws DaoException { byStableId.clear(); byInternalId.clear(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoCancerStudy.class); pstmt = con.prepareStatement("TRUNCATE TABLE cancer_study"); pstmt.executeUpdate(); } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoCancerStudy.class, con, pstmt, rs); } } /** * Deletes the Specified Cancer Study. * * @param internalCancerStudyId Internal Cancer Study ID. * @throws DaoException Database Error. */ static void deleteCancerStudy(int internalCancerStudyId) throws DaoException { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JdbcUtil.getDbConnection(DaoCancerStudy.class); // this is a hacky way to delete all associated data with on cancer study. // ideally database dependency should be modeled with option of delete on cascade. // remember to update this code if new tables are added or existing tables are changed. String[] sqls = { "delete from case_cna_event where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from genetic_alteration where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from genetic_profile_cases where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from case_profile where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from mutation where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from mutation_count where GENETIC_PROFILE_ID IN (select GENETIC_PROFILE_ID from genetic_profile where CANCER_STUDY_ID=?);", "delete from case_list_list where LIST_ID IN (select LIST_ID from case_list where CANCER_STUDY_ID=?);", "delete from clinical where CANCER_STUDY_ID=?;", "delete from copy_number_seg where CANCER_STUDY_ID=?;", "delete from case_list where CANCER_STUDY_ID=?;", "delete from genetic_profile where CANCER_STUDY_ID=?;", "delete from gistic_to_gene where GISTIC_ROI_ID IN (select GISTIC_ROI_ID from gistic where CANCER_STUDY_ID=?);", "delete from gistic where CANCER_STUDY_ID=?;", "delete from mut_sig where CANCER_STUDY_ID=?;", "delete from protein_array_data where CANCER_STUDY_ID=?;", "delete from protein_array_cancer_study where CANCER_STUDY_ID=?;", "delete from treatment where CANCER_STUDY_ID=?;", "delete from diagnostic where CANCER_STUDY_ID=?;", "delete from lab_test where CANCER_STUDY_ID=?;", "delete from cancer_study where CANCER_STUDY_ID=?;" }; for (String sql : sqls) { pstmt = con.prepareStatement(sql); pstmt.setInt(1, internalCancerStudyId); pstmt.executeUpdate(); } } catch (SQLException e) { throw new DaoException(e); } finally { JdbcUtil.closeAll(DaoCancerStudy.class, con, pstmt, rs); } reCache(); } /** * Extracts Cancer Study JDBC Results. */ private static CancerStudy extractCancerStudy(ResultSet rs) throws SQLException { CancerStudy cancerStudy = new CancerStudy(rs.getString("NAME"), rs.getString("DESCRIPTION"), rs.getString("CANCER_STUDY_IDENTIFIER"), rs.getString("TYPE_OF_CANCER_ID"), rs.getBoolean("PUBLIC")); cancerStudy.setPmid(rs.getString("PMID")); cancerStudy.setCitation(rs.getString("CITATION")); cancerStudy.setGroups(rs.getString("GROUPS")); cancerStudy.setInternalId(rs.getInt("CANCER_STUDY_ID")); return cancerStudy; } }
package net.mostlyoriginal.game.system.render; import com.artemis.Aspect; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.EntitySystem; import com.artemis.annotations.Wire; import com.artemis.utils.ImmutableBag; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Interpolation; import net.mostlyoriginal.api.component.basic.Pos; import net.mostlyoriginal.game.G; import net.mostlyoriginal.game.component.Layer; import net.mostlyoriginal.game.component.Routable; import net.mostlyoriginal.game.component.Team; import net.mostlyoriginal.game.component.TeamMember; import net.mostlyoriginal.game.component.buildings.Techpoint; import net.mostlyoriginal.game.component.ui.RenderMask; import net.mostlyoriginal.game.manager.LayerManager; import java.util.LinkedList; /** * Estimate what techpoints will be able to pressure resource towers * most effectively. * <p/> * Since teams have different speeds it matters who owns techpoints * to determine who has the greatest claim to a techpoint. * * @author Daan van Yperen */ @Wire public class DomainSystem extends EntitySystem { public static final int ORTHO_MOVEMENT = 10; public static final int DIAGO_MOVEMENT = 14; public static final int MAX_SECONDS_RADIUS = 27; protected LayerManager layerManager; public boolean dirty = true; protected ComponentMapper<Routable> mRoutable; protected ComponentMapper<TeamMember> mTeamMember; public DomainSystem() { super(Aspect.getAspectForAll(Routable.class, Pos.class, Techpoint.class)); } @Override protected void initialize() { } @Override protected void processEntities(ImmutableBag<Entity> entities) { if (dirty) { dirty = false; Layer layer = layerManager.getLayer("DOMAINS", RenderMask.Mask.TEAM_DOMAINS); layerManager.clearWithMap(layer, Color.WHITE, 0.3f); for (Team team : Team.values()) { floodFill(layerManager.getTeamNavLayer(team), layer, entities, team); } } } public class Node { public final int x; public final int y; public int totalCost; public Node parent; private Node(int x, int y, int totalCost) { this.x = x; this.y = y; this.totalCost = totalCost; } public int totalDistance() { return totalCost; } } LinkedList<Node> open = new LinkedList<Node>(); int xOff[] = {-1, 0, 1, 1, 1, 0, -1, -1}; int yOff[] = {-1, -1, -1, 0, 1, 1, 1, 0}; public Node floodFill(Layer layerRaw, Layer layerOut, ImmutableBag<Entity> entities, Team team) { open.clear(); boolean[] closed = new boolean[layerOut.pixmap.getHeight() * layerOut.pixmap.getWidth()]; for (int i = 0, s = entities.size(); i < s; i++) { final Entity e = entities.get(i); final Routable routable = mRoutable.get(e); if ( mTeamMember.has(e)) { if ( mTeamMember.get(e).team == team ) { createUpdateNode(routable.getX(), routable.getY(), null, false); } } } // calculate max route length, in pixels * 10. float maxRouteLength = calculateDistance(team, MAX_SECONDS_RADIUS); Color colorNear = new Color(team.getPathColor()); Color colorFar = new Color(team.getPathColor()); colorFar.a = 0f; colorFar.g = 1f; Color vTmp = new Color(); while (!open.isEmpty()) { final Node node = open.pollFirst(); closed[node.x + node.y * layerOut.pixmap.getWidth() ] = true; for (int i = 0; i < 8; i++) { final int childX = node.x + xOff[i]; final int childY = node.y + yOff[i]; int rawColor = layerRaw.pixmap.getPixel(childX, layerOut.pixmap.getHeight() - childY); boolean isWalkable= ((rawColor & 0x000000ff)) / 255f >= 0.5f; // node not closed yet and location walkable? ONWARD! if (!closed[childX + childY * layerOut.pixmap.getWidth()] && isWalkable) { final boolean diagonal = xOff[i] != 0 && yOff[i] != 0; final Node childNode = createUpdateNode(childX, childY,node, diagonal); // apply maximum distance for searches to keep things snappy. if (childNode.totalCost > maxRouteLength) { open.remove(childNode); closed[childNode.x + childNode.y * layerOut.pixmap.getWidth() ] = true; } else { // create crossbar style. if ( (childX + childY + team.ordinal() * 4) % 8 < 4 ) { float tween = childNode.totalCost / maxRouteLength; vTmp.r = Interpolation.pow2Out.apply(colorNear.r, colorFar.r, tween); vTmp.g = Interpolation.pow2Out.apply(colorNear.g, colorFar.g, tween); vTmp.b = Interpolation.pow2Out.apply(colorNear.b, colorFar.b, tween); vTmp.a = Interpolation.pow2Out.apply(colorNear.a, colorFar.a, tween); layerOut.pixmap.setColor(vTmp); layerOut.pixmap.drawPixel(childX, layerOut.pixmap.getHeight() - childY); } } } } } return null; } private float calculateDistance(Team team, int seconds) { return ((Math.round(team.getAvgSpeed() * seconds)) / G.PIXELS_TO_UNITS) * ORTHO_MOVEMENT; } private Node createUpdateNode(int x, int y, Node parent, boolean diagonal) { final int updatedCost = parent != null ? parent.totalCost + (diagonal ? DIAGO_MOVEMENT : ORTHO_MOVEMENT) : 0; for (Node node : open) { if (node.x == x && node.y == y) { if (updatedCost < node.totalCost) { node.totalCost = updatedCost; node.parent = parent; } return node; } } final Node node = new Node(x, y, updatedCost); node.parent = parent; open.add(node); return node; } }
package com.reactnativenavigation.layouts; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.RelativeLayout; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.WritableMap; import com.reactnativenavigation.NavigationApplication; import com.reactnativenavigation.events.EventBus; import com.reactnativenavigation.events.ScreenChangedEvent; import com.reactnativenavigation.params.ActivityParams; import com.reactnativenavigation.params.FabParams; import com.reactnativenavigation.params.LightBoxParams; import com.reactnativenavigation.params.ScreenParams; import com.reactnativenavigation.params.SideMenuParams; import com.reactnativenavigation.params.SlidingOverlayParams; import com.reactnativenavigation.params.SnackbarParams; import com.reactnativenavigation.params.TitleBarButtonParams; import com.reactnativenavigation.params.TitleBarLeftButtonParams; import com.reactnativenavigation.screens.Screen; import com.reactnativenavigation.screens.ScreenStack; import com.reactnativenavigation.views.BottomTabs; import com.reactnativenavigation.views.LightBox; import com.reactnativenavigation.views.MenuButtonOnClickListener; import com.reactnativenavigation.views.SideMenu; import com.reactnativenavigation.views.SideMenu.Side; import com.reactnativenavigation.views.SnackbarAndFabContainer; import com.reactnativenavigation.views.slidingOverlay.SlidingOverlay; import com.reactnativenavigation.views.slidingOverlay.SlidingOverlaysQueue; import java.util.List; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; public class BottomTabsLayout extends BaseLayout implements AHBottomNavigation.OnTabSelectedListener, MenuButtonOnClickListener { private ActivityParams params; private SnackbarAndFabContainer snackbarAndFabContainer; private BottomTabs bottomTabs; private ScreenStack[] screenStacks; private ScreenStack extraScreenStack; private String selectedPath; private final SideMenuParams leftSideMenuParams; private final SideMenuParams rightSideMenuParams; private final SlidingOverlaysQueue slidingOverlaysQueue = new SlidingOverlaysQueue(); private @Nullable SideMenu sideMenu; private int currentStackIndex = 0; private LightBox lightBox; public BottomTabsLayout(AppCompatActivity activity, ActivityParams params) { super(activity); this.params = params; selectedPath = params.selectedPath; leftSideMenuParams = params.leftSideMenuParams; rightSideMenuParams = params.rightSideMenuParams; screenStacks = new ScreenStack[params.tabParams.size()]; createLayout(); } private void createLayout() { createSideMenu(); createBottomTabs(); addBottomTabs(); addScreenStacks(); createSnackbarContainer(); showInitialScreenStack(); } private void createSideMenu() { if (leftSideMenuParams == null && rightSideMenuParams == null) { return; } sideMenu = new SideMenu(getContext(), leftSideMenuParams, rightSideMenuParams); RelativeLayout.LayoutParams lp = new LayoutParams(MATCH_PARENT, MATCH_PARENT); addView(sideMenu, lp); } private void addScreenStacks() { for (int i = screenStacks.length - 1; i >= 0; i createAndAddScreens(i); } ScreenParams screenParams = params.screenParams; ScreenStack newStack = new ScreenStack(getActivity(), getScreenStackParent(), screenParams.getNavigatorId(), this, this); if (this.selectedPath != null && this.getTabIndexForScreenId(this.selectedPath) < 0) { newStack.pushInitialScreen(screenParams, createScreenLayoutParams(screenParams)); } extraScreenStack = newStack; } private void createAndAddScreens(int position) { ScreenParams screenParams = params.tabParams.get(position); ScreenStack newStack = new ScreenStack(getActivity(), getScreenStackParent(), screenParams.getNavigatorId(), this, this); newStack.pushInitialScreen(screenParams, createScreenLayoutParams(screenParams)); screenStacks[position] = newStack; } public RelativeLayout getScreenStackParent() { return sideMenu == null ? this : sideMenu.getContentContainer(); } @NonNull private LayoutParams createScreenLayoutParams(ScreenParams params) { LayoutParams lp = new LayoutParams(MATCH_PARENT, MATCH_PARENT); if (params.styleParams.drawScreenAboveBottomTabs) { lp.addRule(RelativeLayout.ABOVE, bottomTabs.getId()); } return lp; } private void createBottomTabs() { bottomTabs = new BottomTabs(getContext()); bottomTabs.addTabs(params.tabParams, this); } private void addBottomTabs() { LayoutParams lp = new LayoutParams(MATCH_PARENT, WRAP_CONTENT); lp.addRule(ALIGN_PARENT_BOTTOM); getScreenStackParent().addView(bottomTabs, lp); } private void createSnackbarContainer() { snackbarAndFabContainer = new SnackbarAndFabContainer(getContext(), this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT); lp.addRule(ABOVE, bottomTabs.getId()); snackbarAndFabContainer.setClickable(false); getScreenStackParent().addView(snackbarAndFabContainer, lp); } private void showInitialScreenStack() { int initialScreen = 0; if (this.selectedPath != null) { initialScreen = getTabIndexForScreenId(this.selectedPath); } if (initialScreen > -1) { showStackAndUpdateStyle(screenStacks[initialScreen]); EventBus.instance.post(new ScreenChangedEvent(screenStacks[initialScreen].peek().getScreenParams())); } else if (this.selectedPath != null && initialScreen < 0) { showStackAndUpdateStyle(extraScreenStack); } bottomTabs.setCurrentItem(initialScreen); } private int getTabIndexForScreenId(String path) { int leni = screenStacks.length; for (int i = 0; i < leni; ++i) { ScreenStack stack = screenStacks[i]; if (stack.rootScreenId().equals(path)) { return i; } } return -1; } @Override public View asView() { return this; } @Override public boolean onBackPressed() { if (getCurrentScreenStack().handleBackPressInJs()) { return true; } if (getCurrentScreenStack().canPop()) { getCurrentScreenStack().pop(true); setBottomTabsStyleFromCurrentScreen(); EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); return true; } else { return getCurrentScreenStack().getDisableBackNavigation(); } } @Override public void setTopBarVisible(String screenInstanceId, boolean hidden, boolean animated) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setScreenTopBarVisible(screenInstanceId, hidden, animated); } } public void setBottomTabsVisible(boolean hidden, boolean animated) { bottomTabs.setVisibility(hidden, animated); } @Override public void setTitleBarTitle(String screenInstanceId, String title) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setScreenTitleBarTitle(screenInstanceId, title); } if (extraScreenStack != null) { extraScreenStack.setScreenTitleBarTitle(screenInstanceId, title); } } @Override public void setTitleBarSubtitle(String screenInstanceId, String subtitle) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setScreenTitleBarSubtitle(screenInstanceId, subtitle); } if (extraScreenStack != null) { extraScreenStack.setScreenTitleBarSubtitle(screenInstanceId, subtitle); } } @Override public void setTitleBarRightButtons(String screenInstanceId, String navigatorEventId, List<TitleBarButtonParams> titleBarButtons) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setScreenTitleBarRightButtons(screenInstanceId, navigatorEventId, titleBarButtons); } if (extraScreenStack != null) { extraScreenStack.setScreenTitleBarRightButtons(screenInstanceId, navigatorEventId, titleBarButtons); } } @Override public void setTitleBarLeftButton(String screenInstanceId, String navigatorEventId, TitleBarLeftButtonParams titleBarLeftButtonParams) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setScreenTitleBarLeftButton(screenInstanceId, navigatorEventId, titleBarLeftButtonParams); } if (extraScreenStack != null) { extraScreenStack.setScreenTitleBarLeftButton(screenInstanceId, navigatorEventId, titleBarLeftButtonParams); } } @Override public void setFab(String screenInstanceId, String navigatorEventId, FabParams fabParams) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].setFab(screenInstanceId, fabParams); } if (extraScreenStack != null) { extraScreenStack.setFab(screenInstanceId, fabParams); } } @Override public void updateScreenStyle(String screenInstanceId, Bundle styleParams) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].updateScreenStyle(screenInstanceId, styleParams); } if (extraScreenStack != null) { extraScreenStack.updateScreenStyle(screenInstanceId, styleParams); } } @Override public String getCurrentlyVisibleScreenId() { return getCurrentScreen().getScreenParams().getScreenId(); } @Override public void selectTopTabByTabIndex(String screenInstanceId, int index) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].selectTopTabByTabIndex(screenInstanceId, index); } if (extraScreenStack != null) { extraScreenStack.selectTopTabByTabIndex(screenInstanceId, index); } } @Override public void selectTopTabByScreen(String screenInstanceId) { for (int i = 0; i < bottomTabs.getItemsCount(); i++) { screenStacks[i].selectTopTabByScreen(screenInstanceId); } if (extraScreenStack != null) { extraScreenStack.selectTopTabByScreen(screenInstanceId); } } @Override public void toggleSideMenuVisible(boolean animated, Side side) { if (sideMenu != null) { sideMenu.toggleVisible(animated, side); } } @Override public void setSideMenuVisible(boolean animated, boolean visible, Side side) { if (sideMenu != null) { sideMenu.setVisible(visible, animated, side); } } @Override public void disableOpenGesture(boolean disableOpenGesture) { if (sideMenu != null) { sideMenu.disableOpenGesture(disableOpenGesture); } } @Override public void disableBackNavigation(boolean disableBackNavigation) { getCurrentScreenStack().setDisableBackNavigation(disableBackNavigation); } @Override public void showSnackbar(SnackbarParams params) { final String eventId = getCurrentScreenStack().peek().getNavigatorEventId(); snackbarAndFabContainer.showSnackbar(eventId, params); } @Override public void dismissSnackbar() { snackbarAndFabContainer.dismissSnackbar(); } @Override public void showLightBox(LightBoxParams params) { if (lightBox == null) { lightBox = new LightBox(getActivity(), new Runnable() { @Override public void run() { lightBox = null; } }, params); lightBox.show(); } } @Override public void dismissLightBox() { if (lightBox != null) { lightBox.hide(); lightBox = null; } } @Override public void showSlidingOverlay(final SlidingOverlayParams params) { slidingOverlaysQueue.add(new SlidingOverlay(this, params)); } @Override public void hideSlidingOverlay() { slidingOverlaysQueue.remove(); } @Override public void onModalDismissed() { EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); } @Override public boolean containsNavigator(String navigatorId) { // Unused return false; } @Override public Screen getCurrentScreen() { return getCurrentScreenStack().peek(); } public void selectBottomTabByTabIndex(Integer index) { boolean wasSelected = bottomTabs.getCurrentItem() == index; bottomTabs.setCurrentItem(index, false); this.onTabSelected(index, wasSelected, false); } public void selectBottomTabByNavigatorId(String navigatorId) { bottomTabs.setCurrentItem(getScreenStackIndex(navigatorId)); } @Override public void push(ScreenParams params) { ScreenStack screenStack = getScreenStack(params.getNavigatorId()); screenStack.push(params, createScreenLayoutParams(params)); if (isCurrentStack(screenStack)) { bottomTabs.setStyleFromScreen(params.styleParams); EventBus.instance.post(new ScreenChangedEvent(params)); } } @Override public void pop(ScreenParams params) { getCurrentScreenStack().pop(params.animateScreenTransitions, new ScreenStack.OnScreenPop() { @Override public void onScreenPopAnimationEnd() { setBottomTabsStyleFromCurrentScreen(); EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); } }); } @Override public void popToRoot(ScreenParams params) { getCurrentScreenStack().popToRoot(params.animateScreenTransitions, new ScreenStack.OnScreenPop() { @Override public void onScreenPopAnimationEnd() { setBottomTabsStyleFromCurrentScreen(); EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); } }); } @Override public void newStack(final ScreenParams params) { ScreenStack screenStack = getScreenStack(params.getNavigatorId()); screenStack.newStack(params, createScreenLayoutParams(params)); if (isCurrentStack(screenStack)) { bottomTabs.setStyleFromScreen(params.styleParams); EventBus.instance.post(new ScreenChangedEvent(params)); } } public void destroyStacks() { if (screenStacks != null) { for (ScreenStack screenStack : screenStacks) { screenStack.destroy(); } } screenStacks = null; } @Override public void destroy() { snackbarAndFabContainer.destroy(); destroyStacks(); if (sideMenu != null) { sideMenu.destroy(); } if (lightBox != null) { lightBox.destroy(); lightBox = null; } slidingOverlaysQueue.destroy(); } @Override public boolean onTabSelected(int position, boolean wasSelected) { return this.onTabSelected(position, wasSelected, true); } private boolean onTabSelected(int position, boolean wasSelected, boolean sendEventToJS) { if (wasSelected && sendEventToJS) { sendTabReselectedEventToJs(); return false; } final int unselectedTabIndex = currentStackIndex; hideCurrentStack(); showNewStack(position); EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); if (sendEventToJS) { sendTabSelectedEventToJs(position, unselectedTabIndex); } return true; } private void sendTabSelectedEventToJs(int selectedTabIndex, int unselectedTabIndex) { String navigatorEventId = getCurrentScreenStack().peek().getNavigatorEventId(); WritableMap data = createTabSelectedEventData(selectedTabIndex, unselectedTabIndex); NavigationApplication.instance.getEventEmitter().sendNavigatorEvent("bottomTabSelected", navigatorEventId, data); data = createTabSelectedEventData(selectedTabIndex, unselectedTabIndex); NavigationApplication.instance.getEventEmitter().sendNavigatorEvent("bottomTabSelected", data); } private WritableMap createTabSelectedEventData(int selectedTabIndex, int unselectedTabIndex) { WritableMap data = Arguments.createMap(); data.putInt("selectedTabIndex", selectedTabIndex); data.putInt("unselectedTabIndex", unselectedTabIndex); return data; } private void sendTabReselectedEventToJs() { WritableMap data = Arguments.createMap(); String navigatorEventId = getCurrentScreenStack().peek().getNavigatorEventId(); NavigationApplication.instance.getEventEmitter().sendNavigatorEvent("bottomTabReselected", navigatorEventId, data); } private void showNewStack(int position) { if (position > -1) { showStackAndUpdateStyle(screenStacks[position]); currentStackIndex = position; } else { showStackAndUpdateStyle(extraScreenStack); currentStackIndex = -1; } } private void showStackAndUpdateStyle(ScreenStack newStack) { newStack.show(); bottomTabs.setStyleFromScreen(newStack.getCurrentScreenStyleParams()); } private void hideCurrentStack() { ScreenStack currentScreenStack = getCurrentScreenStack(); currentScreenStack.hide(); } private ScreenStack getCurrentScreenStack() { return currentStackIndex > -1 ? screenStacks[currentStackIndex] : extraScreenStack; } private @NonNull ScreenStack getScreenStack(String navigatorId) { int index = getScreenStackIndex(navigatorId); return index > -1 ? screenStacks[index] : extraScreenStack; } public void setBottomTabButtonByIndex(Integer index, ScreenParams params) { bottomTabs.setTabButton(params, index); } public void setBottomTabButtonByNavigatorId(String navigatorId, ScreenParams params) { bottomTabs.setTabButton(params, getScreenStackIndex(navigatorId)); } private int getScreenStackIndex(String navigatorId) throws ScreenStackNotFoundException { for (int i = 0; i < screenStacks.length; i++) { if (screenStacks[i].getNavigatorId().equals(navigatorId)) { return i; } } if (extraScreenStack != null) { return -1; } throw new ScreenStackNotFoundException("Stack " + navigatorId + " not found"); } public void showScreen(String screenId, ScreenParams screenParams) { int tabIndex = this.getTabIndexForScreenId(screenId); if (tabIndex == -1 && (extraScreenStack.empty() || !extraScreenStack.peek().getScreenParams().screenId.equals(screenId))) { extraScreenStack.destroy(); extraScreenStack.pushInitialScreen(screenParams, createScreenLayoutParams(screenParams)); showStackAndUpdateStyle(extraScreenStack); } this.selectBottomTabByTabIndex(tabIndex); } private class ScreenStackNotFoundException extends RuntimeException { ScreenStackNotFoundException(String navigatorId) { super(navigatorId); } } private boolean isCurrentStack(ScreenStack screenStack) { return getCurrentScreenStack() == screenStack; } private void setBottomTabsStyleFromCurrentScreen() { bottomTabs.setStyleFromScreen(getCurrentScreenStack().getCurrentScreenStyleParams()); } @Override public boolean onTitleBarBackButtonClick() { if (getCurrentScreenStack().canPop()) { getCurrentScreenStack().pop(true, new ScreenStack.OnScreenPop() { @Override public void onScreenPopAnimationEnd() { setBottomTabsStyleFromCurrentScreen(); EventBus.instance.post(new ScreenChangedEvent(getCurrentScreenStack().peek().getScreenParams())); } }); return true; } return false; } @Override public void onSideMenuButtonClick(Side side) { final String navigatorEventId = getCurrentScreenStack().peek().getNavigatorEventId(); NavigationApplication.instance.getEventEmitter().sendNavigatorEvent("sideMenu", navigatorEventId); if (sideMenu != null) { sideMenu.openDrawer(side); } } @Override public void setSideMenu(SideMenu sideMenu) { this.sideMenu = sideMenu; } @Override public SideMenu getSideMenu() { return sideMenu; } }
package com.alibaba.weex.util; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.Rect; import android.os.Build; import android.os.Environment; import android.support.design.widget.TabLayout; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ScrollView; import com.taobao.weex.ui.view.WXScrollView; import com.taobao.weex.ui.view.listview.WXRecyclerView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; public class ScreenShot { public static View rootView; public static ArrayList<View> allViews = new ArrayList<View>(); public static View firstScrollView = null; public static View firstListView = null; public static View findFirstScrollerByRootView(View rootView){ View firstScrollView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof ScrollView){ firstScrollView = view; break; } } } return firstScrollView; } public static View findFirstListByRootView(View rootView){ View firstListView = null; if(null != rootView){ allViews = ViewUtil.getAllChildViews(rootView); for (View view:allViews ) { if(view instanceof WXRecyclerView){ firstListView = view; break; } } } return firstListView; } private static Bitmap doSanpForListOrScroller(View sanpView){ Bitmap b = null; if(sanpView!=null){ int[] location = new int[2]; sanpView.getLocationInWindow(location); int x = location[0]; int y = location[1]; sanpView = rootView; sanpView.setDrawingCacheEnabled(true); sanpView.buildDrawingCache(); // sanpView = ((View)sanpView.getParent().getParent()); Bitmap bitmap = sanpView.getDrawingCache(); // sanpView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), // View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); // sanpView.layout(0, 0, sanpView.getMeasuredWidth(), sanpView.getMeasuredHeight()); // sanpView.buildDrawingCache(); // Bitmap bitmap = sanpView.getDrawingCache(); // b = bitmap; int sanpWidth = sanpView.getWidth(); Log.e("weex_test", "sanpView.getWidth=="+ sanpWidth); int snapHeight = sanpView.getHeight(); Log.e("weex_test", "sanpView.getHeight==" + snapHeight); // bitmap = Bitmap.createBitmap(sanpWidth+x, snapHeight+x,Bitmap.Config.ARGB_8888); // int width = activity.getWindowManager().getDefaultDisplay().getWidth(); // int height = activity.getWindowManager().getDefaultDisplay().getHeight(); int baseWidth = 750; int baseHeight = 1134; // float heightScale = ((float) baseHeight) / scrollerHeight; float widthScale = ((float) baseWidth) / sanpWidth; Matrix matrix = new Matrix(); matrix.postScale(widthScale, widthScale); Log.e("weex_test", "widthScale=="+widthScale+ "|"+ "Real sanpWidth==" + sanpWidth*widthScale +"|" + "Real snapHeight==" + widthScale*snapHeight + "|" + "sanpView.x=" + x + "|" + "sanpView.y= " + y); b = Bitmap.createBitmap(bitmap, 0, 0, sanpWidth, snapHeight); // b = Bitmap.createBitmap(bitmap, 0, 0, rootView.getWidth(), rootView.getHeight()); // Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh, // Bitmap.Config.ARGB_4444); b = Bitmap.createBitmap(bitmap,0, 0, sanpWidth, snapHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, 0, scrollerWidth, // scrollerHeight, matrix, true); // b = Bitmap.createBitmap(bitmap, 0, statusBarHeight + actionBarHeight, width, // height - statusBarHeight - actionBarHeight, matrix, true); sanpView.destroyDrawingCache(); }else { Log.e("weex_test", "snapshot view is " + sanpView); } return b; } // Gets the Activity screenshots, save to png file private static Bitmap takeScreenShot(Activity activity) { Context ctx = activity.getApplicationContext(); getDiskCacheDir(ctx); View view = activity.getWindow().getDecorView(); rootView = view; firstScrollView = findFirstScrollerByRootView(rootView); firstListView = findFirstListByRootView(rootView); Bitmap snapBitmap = null; // scroller ->list->root if(null !=firstScrollView ){ snapBitmap = doSanpForListOrScroller(firstScrollView); } else { Log.e("weex_test", "firstScrollView is " + firstScrollView); if (null != firstListView){ snapBitmap = doSanpForListOrScroller(firstListView); }else { Log.e("weex_test", "firstListView is " + firstListView); if(null != rootView){ // snapBitmap = doSanpForListOrScroller(rootView); } } } return snapBitmap; } public static Bitmap convertViewToBitmap(View view){ view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); return bitmap; } private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void saveToSD(Bitmap bmp, String dirName,String fileName) throws IOException { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(dirName); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dirName + fileName); Log.d("AssetsFileUtil", dirName + fileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (fos != null) { bmp.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void shoot(Activity activity, String pathName) throws IOException { if(SdCardHelper.isHasSdcard()){ ScreenShot.saveToSD(ScreenShot.takeScreenShot(activity), SdCardHelper.SDCardRoot + "WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); } } // public static void shootAllViews(Activity activity, String pathName) throws IOException { // ScreenShot.saveToSD(ScreenShot.takeScreenShotIncludeDialog(activity, pathName), "sdcard/WeexTest/ScreenShot/", pathName /*+System.currentTimeMillis()*/ + ".png"); public static void takeScreenShotIncludeDialog(Activity activity, String file){ if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(SdCardHelper.SDCardRoot +"WeexTest/ScreenShot/"); if(!dir.exists()){ dir.mkdirs(); } File filePic = new File(SdCardHelper.SDCardRoot + "WeexTest/ScreenShot/"+ file + ".png"); if (!filePic.exists()) { try { filePic.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Falcon.takeScreenshot(activity, filePic); } } public static int getActionBarHeight(Activity activity) { int actionBarHeight = 0; if(activity.getActionBar()!= null){ actionBarHeight = activity.getActionBar().getHeight(); } if (actionBarHeight != 0) return actionBarHeight; final TypedValue tv = new TypedValue(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (activity.getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "android.support.v7.appcompat.R.attr.actionBarSize"); } else if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)){ actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics()); Log.e("actionBarHeight==",actionBarHeight + "actionBarHeight is android.R.attr.actionBarSize"); } } return actionBarHeight; } public static int getStatusBarHeight1(Activity activity){ int result = 0; int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = activity.getResources().getDimensionPixelSize(resourceId); } Log.e("StatusBarHeight==", "StatusBar Height= " + result); return result; } public static int getStatusBarHeight(Activity activity) { int result = 0; Rect rect = new Rect(); Window window = activity.getWindow(); if (window != null) { window.getDecorView().getWindowVisibleDisplayFrame(rect); View v = window.findViewById(Window.ID_ANDROID_CONTENT); android.view.Display display = ((android.view.WindowManager) activity.getSystemService(activity.WINDOW_SERVICE)).getDefaultDisplay(); //return result title bar height int result1 = display.getHeight() - v.getBottom() + rect.top; int result2 = display.getHeight() - v.getBottom(); int result3 = v.getTop() - rect.top; int result4 = display.getHeight() - v.getHeight(); Log.e("StatusBarHeight==", "result1== " + result1 +" result2 = " + result2 + "result3=" + result3 + "result4=" +result4 ) ; } return result; } /** * getDiskCacheDir * @param context * @return */ public static String getDiskCacheDir(Context context) { if (context == null) { return null; } String cachePath; String extDir = "" ; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = context.getExternalCacheDir().getPath(); extDir = Environment.getExternalStorageDirectory().getPath(); } else { cachePath = context.getCacheDir().getPath(); } Log.e("weex_test","cachePath==" + cachePath); Log.e("weex_test","extDir==" + extDir); return cachePath; } }
package org.appcelerator.titanium.view; import java.util.Arrays; import org.appcelerator.kroll.common.Log; import com.nineoldandroids.view.ViewHelper; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.graphics.Path.FillType; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.os.Build; import android.view.View; import android.widget.FrameLayout; import android.view.ViewOutlineProvider; import android.graphics.Outline; /** * This class is a wrapper for Titanium Views with borders. Any view that specifies a border * related property will have a border wrapper view to maintain its border. */ public class TiBorderWrapperView extends FrameLayout { public static final int SOLID = 0; private static final String TAG = "TiBorderWrapperView"; private int color = Color.TRANSPARENT; private int bgColor = Color.TRANSPARENT; private float radius = 0; private float borderWidth = 0; private int alpha = -1; private RectF outerRect, innerRect; private Path innerPath; private Path borderPath; private Paint paint; private View child; private Rect bounds = new Rect(); public TiBorderWrapperView(Context context) { super(context); outerRect = new RectF(); innerRect = new RectF(); paint = new Paint(Paint.ANTI_ALIAS_FLAG); setWillNotDraw(false); } @Override protected void onDraw(Canvas canvas) { updateBorderPath(); drawBorder(canvas); if (radius > 0) { // This still happens sometimes when hw accelerated so, catch and warn try { // If the view's background color is not transparent, we draw the background first if (bgColor != Color.TRANSPARENT) { paint.setColor(bgColor); canvas.drawPath(innerPath, paint); } // Then we clip it to ensure anti-aliasing. canvas.clipPath(innerPath); // Then we clear the clipped region so when the view draws, alpha doesn't stack if bgColor // has an alpha that is less than 1. We then reset the color and alpha. if (bgColor != Color.TRANSPARENT) { canvas.drawColor(0, PorterDuff.Mode.CLEAR); setAlphaAndColor(); } } catch (Exception e) { Log.w(TAG, "clipPath failed on canvas: " + e.getMessage(), Log.DEBUG_MODE); } } else { canvas.clipRect(innerRect); } } private void updateBorderPath() { getDrawingRect(bounds); outerRect.set(bounds); int padding = 0; int maxPadding = 0; // cap padding to current bounds maxPadding = (int) Math.min(outerRect.right / 2, outerRect.bottom / 2); padding = (int) Math.min(borderWidth, maxPadding); innerRect.set(bounds.left + padding, bounds.top + padding, bounds.right - padding, bounds.bottom - padding); if (radius > 0) { float outerRadii[] = new float[8]; Arrays.fill(outerRadii, radius); borderPath = new Path(); borderPath.addRoundRect(outerRect, outerRadii, Direction.CW); borderPath.setFillType(FillType.EVEN_ODD); innerPath = new Path(); innerPath.setFillType(FillType.EVEN_ODD); if (radius - padding > 0) { float innerRadii[] = new float[8]; Arrays.fill(innerRadii, radius - padding); innerPath.addRoundRect(innerRect, innerRadii, Direction.CW); borderPath.addRoundRect(innerRect, innerRadii, Direction.CCW); } else { innerPath.addRect(innerRect, Direction.CW); borderPath.addRect(innerRect, Direction.CCW); } } else { borderPath = new Path(); borderPath.addRect(outerRect, Direction.CW); borderPath.addRect(innerRect, Direction.CCW); borderPath.setFillType(FillType.EVEN_ODD); } // set the outline for the view in order to use elevation ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setRoundRect(bounds, radius); } }; setOutlineProvider(viewOutlineProvider); } private void drawBorder(Canvas canvas) { setAlphaAndColor(); canvas.drawPath(borderPath, paint); } private void setAlphaAndColor() { paint.setColor(color); if (alpha > -1) { paint.setAlpha(alpha); } } public void setColor(int color) { this.color = color; } public void setBgColor(int color) { this.bgColor = color; } public void setRadius(float radius) { this.radius = radius; } public void setBorderWidth(float borderWidth) { this.borderWidth = borderWidth; } @Override public boolean onSetAlpha(int alpha) { if (Build.VERSION.SDK_INT < 11) { /* * This is an ugly hack. ViewHelper.setAlpha does not work on border when * alpha < 1. So we are going to manage alpha animation for ourselves and our * child view manually. This needs to be researched and factored out. * * TIMOB-17287 */ this.alpha = alpha; float falpha = alpha/255.0f; if (child == null) { try { child = getChildAt(0); } catch (Throwable t) { //Ignore this error. child = null; } } if (child != null) { //Set alpha of child view ViewHelper.setAlpha(child, falpha); } return true; } return false; } }
package org.sanelib.eboss.api.converters.client; import com.google.common.base.Strings; import org.sanelib.eboss.api.converters.DtoToCommandConverter; import org.sanelib.eboss.api.dto.client.ClientDTO; import org.sanelib.eboss.common.utils.DateHelper; import org.sanelib.eboss.core.commands.ProcessCommand; import org.sanelib.eboss.core.commands.client.AddClient; import org.sanelib.eboss.core.exceptions.ProcessError; public class AddClientConverter implements DtoToCommandConverter<ClientDTO> { @Override public ProcessCommand convert(ClientDTO dto, ProcessError processError) throws NoSuchFieldException, IllegalAccessException { AddClient command= new AddClient(); if(Strings.isNullOrEmpty(dto.getClientId())){ processError.addError("common.field.required", "client_id", "domain.customer.client_id"); }else{ command.setClientId(dto.getClientId()); } if(Strings.isNullOrEmpty(dto.getClientSecret())){ processError.addError("common.field.required", "client_secret", "domain.customer.client_secret"); }else{ command.setClientSecret(dto.getClientSecret()); } if(Strings.isNullOrEmpty(dto.getClientName())){ processError.addError("common.field.required", "client_name", "domain.customer.client_name"); }else{ command.setClientName(dto.getClientName()); } command.setDescription(dto.getDescription()); if(Strings.isNullOrEmpty(dto.getClientUrl())){ processError.addError("common.field.required", "client_url", "domain.customer.client_url"); }else{ command.setClientUrl(dto.getClientUrl()); } if(Strings.isNullOrEmpty(dto.getClientType())){ processError.addError("common.field.required", "client_type", "domain.customer.client_type"); }else{ command.setClientType(dto.getClientType()); } command.setScope(dto.getScope()); command.setRedirectUri(dto.getRedirectUri()); if(Strings.isNullOrEmpty(dto.getRegdate())){ processError.addError("common.field.required", "regdate", "domain.customer.regdate"); }else{ command.setRegdate(DateHelper.fromDateString((dto.getRegdate()))); } return command; } }
package com.intellij.ide.dnd; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Disposer; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.GeometryUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.dnd.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; public class DnDManagerImpl extends DnDManager implements ProjectComponent, DnDEvent.DropTargetHighlightingType { private static final Logger LOG = Logger.getInstance("com.intellij.ide.dnd.DnDManager"); static final @NonNls String SOURCE_KEY = "DnD Source"; static final @NonNls String TARGET_KEY = "DnD Target"; public static final Key<Pair<Image, Point>> DRAGGED_IMAGE_KEY = new Key<Pair<Image, Point>>("draggedImage"); private DnDEventImpl myCurrentEvent; private DnDEvent myLastHighlightedEvent; private static DnDTarget NULL_TARGET = new NullTarget(); private DnDTarget myLastProcessedTarget = NULL_TARGET; private DragSourceContext myCurrentDragContext; private Component myLastProcessedOverComponent; private Point myLastProcessedPoint; private String myLastMessage; private DnDEvent myLastProcessedEvent; private DragGestureListener myDragGestureListener = new MyDragGestureListnener(); private DropTargetListener myDropTargetListener = new MyDropTargetListener(); private static final Image EMPTY_IMAGE = new BufferedImage(1, 1, Transparency.TRANSLUCENT); private Timer myTooltipTimer = new Timer(ToolTipManager.sharedInstance().getInitialDelay(), new ActionListener() { public void actionPerformed(ActionEvent e) { onTimer(); } }); private Runnable myHightlighterShowRequest; private Rectangle myLastHighlightedRec; private int myLastProcessedAction; public void projectOpened() { } public void projectClosed() { } @NotNull public String getComponentName() { return "FabriqueDnDManager"; } public void initComponent() { myTooltipTimer.start(); } public void disposeComponent() { myTooltipTimer.stop(); } public void registerSource(@NotNull final AdvancedDnDSource source) { if (!GraphicsEnvironment.isHeadless()) { final JComponent c = source.getComponent(); registerSource(source, c); final DnDEnabler enabler = new DnDEnabler(source); c.putClientProperty(DnDEnabler.KEY, enabler); } } public void registerSource(DnDSource source, JComponent component) { if (!GraphicsEnvironment.isHeadless()) { component.putClientProperty(SOURCE_KEY, source); final DragSource defaultDragSource = DragSource.getDefaultDragSource(); defaultDragSource.createDefaultDragGestureRecognizer(component, DnDConstants.ACTION_COPY_OR_MOVE, myDragGestureListener); } } public void unregisterSource(AdvancedDnDSource source) { final JComponent c = source.getComponent(); if (c != null) { final DnDEnabler enabler = (DnDEnabler)c.getClientProperty(DnDEnabler.KEY); if (enabler != null) { Disposer.dispose(enabler); c.putClientProperty(DnDEnabler.KEY, null); } } unregisterSource(source, c); } public void unregisterSource(DnDSource source, JComponent component) { component.putClientProperty(SOURCE_KEY, null); } public void registerTarget(DnDTarget target, JComponent component) { if (!GraphicsEnvironment.isHeadless()) { component.putClientProperty(TARGET_KEY, target); new DropTarget(component, DnDConstants.ACTION_COPY_OR_MOVE, myDropTargetListener); } } public void unregisterTarget(DnDTarget target, JComponent component) { component.putClientProperty(TARGET_KEY, null); } private void updateCurrentEvent(Component aComponentOverDragging, Point aPoint, int nativeAction) { LOG.debug("updateCurrentEvent: " + aComponentOverDragging); if (myCurrentDragContext == null) return; myCurrentEvent.updateAction(getDnDActionForPlatformAction(nativeAction)); myCurrentEvent.setPoint(aPoint); myCurrentEvent.setHandlerComponent(aComponentOverDragging); boolean samePoint = myCurrentEvent.getPoint().equals(myLastProcessedPoint); boolean sameComponent = myCurrentEvent.getCurrentOverComponent().equals(myLastProcessedOverComponent); boolean sameAction = (nativeAction == myLastProcessedAction); LOG.debug("updateCurrentEvent: point:" + aPoint); LOG.debug("updateCurrentEvent: action:" + nativeAction); if (samePoint && sameComponent && sameAction) { return; } DnDTarget target = getTarget(aComponentOverDragging); DnDTarget immediateTarget = target; Component eachParent = aComponentOverDragging; final Pair<Image, Point> pair = myCurrentEvent.getUserData(DRAGGED_IMAGE_KEY); if (pair != null) { target.updateDraggedImage(pair.first, aPoint, pair.second); } LOG.debug("updateCurrentEvent: action:" + nativeAction); while (true) { boolean canGoToParent = update(target); if (myCurrentEvent.isDropPossible()) { if (myCurrentEvent.wasDelegated()) { target = myCurrentEvent.getDelegatedTarget(); } break; } if (!canGoToParent) { break; } eachParent = findAllowedParentComponent(eachParent); if (eachParent == null) { break; } target = getTarget(eachParent); } LOG.debug("updateCurrentEvent: target:" + target); LOG.debug("updateCurrentEvent: immediateTarget:" + immediateTarget); if (!myCurrentEvent.isDropPossible() && !immediateTarget.equals(target)) { update(immediateTarget); } updateCursor(); final Container current = (Container)myCurrentEvent.getCurrentOverComponent(); final Point point = myCurrentEvent.getPointOn(getLayeredPane(current)); Rectangle inPlaceRect = new Rectangle(point.x - 5, point.y - 5, 5, 5); if (!myCurrentEvent.equals(myLastProcessedEvent)) { hideCurrentHighlighter(); } boolean sameTarget = myLastProcessedTarget.equals(target); if (sameTarget) { if (myCurrentEvent.isDropPossible()) { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { if (!Highlighters.isVisibleExcept(TEXT | ERROR_TEXT)) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { hideCurrentHighlighter(); myLastProcessedTarget.cleanUpOnLeave(); myCurrentEvent.clearDropHandler(); restartTimer(); if (!myCurrentEvent.isDropPossible()) { queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } myLastProcessedTarget = target; myLastProcessedPoint = myCurrentEvent.getPoint(); myLastProcessedOverComponent = myCurrentEvent.getCurrentOverComponent(); myLastProcessedAction = myCurrentEvent.getAction().getActionId(); myLastProcessedEvent = (DnDEvent)myCurrentEvent.clone(); } private void updateCursor() { Cursor cursor; if (myCurrentEvent.isDropPossible()) { cursor = myCurrentEvent.getCursor(); if (cursor == null) { cursor = myCurrentEvent.getAction().getCursor(); } } else { cursor = myCurrentEvent.getAction().getRejectCursor(); } myCurrentDragContext.setCursor(cursor); } private void restartTimer() { myTooltipTimer.restart(); } private boolean update(DnDTarget target) { LOG.debug("update target:" + target); myCurrentEvent.clearDelegatedTarget(); final boolean canGoToParent = target.update(myCurrentEvent); String message; if (isMessageProvided(myCurrentEvent)) { message = myCurrentEvent.getExpectedDropResult(); } else { message = ""; } //final WindowManager wm = WindowManager.getInstance(); //final StatusBar statusBar = wm.getStatusBar(target.getProject()); //statusBar.setInfo(message); if (myLastMessage != null && !myLastMessage.equals(message)) { hideCurrentHighlighter(); } myLastMessage = message; return canGoToParent; } private static Component findAllowedParentComponent(Component aComponentOverDragging) { Component eachParent = aComponentOverDragging; while (true) { eachParent = eachParent.getParent(); if (eachParent == null) { return null; } final DnDTarget target = getTarget(eachParent); if (target != NULL_TARGET) { return eachParent; } } } private static DnDSource getSource(Component component) { if (component instanceof JComponent) { return (DnDSource)((JComponent)component).getClientProperty(SOURCE_KEY); } return null; } private static DnDTarget getTarget(Component component) { if (component instanceof JComponent) { DnDTarget target = (DnDTarget)((JComponent)component).getClientProperty(TARGET_KEY); if (target != null) return target; } return NULL_TARGET; } void showHighlighter(final Component aComponent, final int aType, final DnDEvent aEvent) { final Rectangle bounds = aComponent.getBounds(); final Container parent = aComponent.getParent(); showHighlighter(parent, aEvent, bounds, aType); } void showHighlighter(final RelativeRectangle rectangle, final int aType, final DnDEvent aEvent) { final JLayeredPane layeredPane = getLayeredPane(rectangle.getPoint().getComponent()); final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, aEvent, bounds, aType); } void showHighlighter(JLayeredPane layeredPane, final RelativeRectangle rectangle, final int aType, final DnDEvent event) { final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, event, bounds, aType); } private boolean isEventBeingHighlighted(DnDEvent event) { return event.equals(getLastHighlightedEvent()); } private void showHighlighter(final Component parent, final DnDEvent aEvent, final Rectangle bounds, final int aType) { final JLayeredPane layeredPane = getLayeredPane(parent); if (layeredPane == null) { return; } if (isEventBeingHighlighted(aEvent)) { if (GeometryUtil.isWithin(myLastHighlightedRec, aEvent.getPointOn(layeredPane))) { return; } } final Rectangle rectangle = SwingUtilities.convertRectangle(parent, bounds, layeredPane); setLastHighlightedEvent((DnDEvent)((DnDEventImpl)aEvent).clone(), rectangle); Highlighters.hide(); Highlighters.show(aType, layeredPane, rectangle, aEvent); if (isMessageProvided(aEvent)) { queueTooltip(aEvent, layeredPane, rectangle); } else { Highlighters.hide(TEXT | ERROR_TEXT); } } private void queueTooltip(final DnDEvent aEvent, final JLayeredPane aLayeredPane, final Rectangle aRectangle) { myHightlighterShowRequest = new Runnable() { public void run() { if (myCurrentEvent != aEvent) return; Highlighters.hide(TEXT | ERROR_TEXT); if (aEvent.isDropPossible()) { Highlighters.show(TEXT, aLayeredPane, aRectangle, aEvent); } else { Highlighters.show(ERROR_TEXT, aLayeredPane, aRectangle, aEvent); } } }; } private static boolean isMessageProvided(final DnDEvent aEvent) { return aEvent.getExpectedDropResult() != null && aEvent.getExpectedDropResult().trim().length() > 0; } void hideCurrentHighlighter() { Highlighters.hide(); myHightlighterShowRequest = null; setLastHighlightedEvent(null, null); } private void onTimer() { if (myHightlighterShowRequest != null) { myHightlighterShowRequest.run(); myHightlighterShowRequest = null; } } private static JLayeredPane getLayeredPane(Component aComponent) { if (aComponent == null) return null; if (aComponent instanceof JLayeredPane) { return (JLayeredPane)aComponent; } if (aComponent instanceof JFrame) { return ((JFrame)aComponent).getRootPane().getLayeredPane(); } if (aComponent instanceof JDialog) { return ((JDialog)aComponent).getRootPane().getLayeredPane(); } final JFrame frame = ((JFrame)SwingUtilities.getWindowAncestor(aComponent)); if (frame == null) { return null; } return frame.getLayeredPane(); } private static class NullTarget implements DnDTarget { public boolean update(DnDEvent aEvent) { aEvent.setDropPossible(false, "You cannot drop anything here"); return false; } public void drop(DnDEvent aEvent) { } public void cleanUpOnLeave() { } public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) { } } DnDEvent getCurrentEvent() { return myCurrentEvent; } private DnDEvent getLastHighlightedEvent() { return myLastHighlightedEvent; } private void setLastHighlightedEvent(DnDEvent lastHighlightedEvent, Rectangle aRectangle) { myLastHighlightedEvent = lastHighlightedEvent; myLastHighlightedRec = aRectangle; } private void resetCurrentEvent(@NonNls String s) { myCurrentEvent = null; LOG.debug("Reset Current Event: " + s); } private class MyDragGestureListnener implements DragGestureListener { public void dragGestureRecognized(DragGestureEvent dge) { final DnDSource source = getSource(dge.getComponent()); if (source == null) return; DnDAction action = getDnDActionForPlatformAction(dge.getDragAction()); if (source.canStartDragging(action, dge.getDragOrigin())) { if (myCurrentEvent == null) { // Actually, under Linux it is possible to get 2 or more dragGestureRecognized calls for single drag // operation. To reproduce: // 1. Do D-n-D in Styles tree // 2. Make an attempt to do D-n-D in Services tree // 3. Do D-n-D in Styles tree again. LOG.debug("Starting dragging for " + action); hideCurrentHighlighter(); final DnDDragStartBean dnDDragStartBean = source.startDragging(action, dge.getDragOrigin()); myCurrentEvent = new DnDEventImpl(DnDManagerImpl.this, action, dnDDragStartBean.getAttachedObject(), dnDDragStartBean.getPoint()); myCurrentEvent.setOrgPoint(dge.getDragOrigin()); Pair<Image, Point> pair = source.createDraggedImage(action, dge.getDragOrigin()); if (pair == null) { pair = new Pair<Image, Point>(EMPTY_IMAGE, new Point(0, 0)); } if (!DragSource.isDragImageSupported()) { // not all of the platforms supports image dragging (mswin doesn't, for example). myCurrentEvent.putUserData(DRAGGED_IMAGE_KEY, pair); } // mac osx fix: it will draw a border with size of the dragged component if there is no image provided. dge.startDrag(DragSource.DefaultCopyDrop, pair.first, pair.second, myCurrentEvent, new MyDragSourceListener(source)); // check if source is also a target // DnDTarget target = getTarget(dge.getComponent()); // if( target != null ) { // target.update(myCurrentEvent); } } } } private static DnDAction getDnDActionForPlatformAction(int platformAction) { DnDAction action = null; switch (platformAction) { case DnDConstants.ACTION_COPY: action = DnDAction.COPY; break; case DnDConstants.ACTION_MOVE: action = DnDAction.MOVE; break; case DnDConstants.ACTION_LINK: action = DnDAction.LINK; break; default: break; } return action; } private class MyDragSourceListener implements DragSourceListener { private final DnDSource mySource; public MyDragSourceListener(final DnDSource source) { mySource = source; } public void dragEnter(DragSourceDragEvent dsde) { LOG.debug("dragEnter:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dragOver(DragSourceDragEvent dsde) { LOG.debug("dragOver:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dropActionChanged(DragSourceDragEvent dsde) { mySource.dropActionChanged(dsde.getGestureModifiers()); } public void dragDropEnd(DragSourceDropEvent dsde) { mySource.dragDropEnd(); myLastProcessedTarget.cleanUpOnLeave(); resetCurrentEvent("dragDropEnd:" + dsde.getDragSourceContext().getComponent()); Highlighters.hide(TEXT | ERROR_TEXT); } public void dragExit(DragSourceEvent dse) { LOG.debug("Stop dragging1"); onDragExit(); } } private class MyDropTargetListener implements DropTargetListener { public void drop(final DropTargetDropEvent dtde) { try { final Component component = dtde.getDropTargetContext().getComponent(); updateCurrentEvent(component, dtde.getLocation(), dtde.getDropAction()); if (myCurrentEvent != null && myCurrentEvent.isDropPossible()) { dtde.acceptDrop(dtde.getDropAction()); // do not wrap this into WriteAction! doDrop(component); if (myCurrentEvent.shouldRemoveHighlightings()) { hideCurrentHighlighter(); } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch (Throwable e) { LOG.error(e); dtde.rejectDrop(); } finally { resetCurrentEvent("Stop dragging2"); } } private void doDrop(Component component) { if (myCurrentEvent.canHandleDrop()) { myCurrentEvent.handleDrop(); } else { getTarget(component).drop(myCurrentEvent); } } public void dragOver(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } public void dragExit(DropTargetEvent dte) { onDragExit(); } public void dragEnter(DropTargetDragEvent dtde) { } public void dropActionChanged(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } } private void onDragExit() { if (myCurrentDragContext != null) { myCurrentDragContext.setCursor(null); } myLastProcessedTarget.cleanUpOnLeave(); hideCurrentHighlighter(); myHightlighterShowRequest = null; } }
package com.parsa_plm.jointelementinspector.fragments; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class PagerAdapter extends FragmentPagerAdapter { private int mNumOfTabs; public PagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } // 20170113: add visual viewer for 3d @Override public Fragment getItem(int position) { switch (position) { case 0: return new OverviewTabFragment(); case 1: return new VisualViewerFragment(); case 2: return new DocumentTabFragment(); case 3: return new PhotoTabFragment(); default: return null; } } @Override public int getCount() { return mNumOfTabs; } }
package com.intellij.ide.dnd; import com.intellij.openapi.application.Application; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.GeometryUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.dnd.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.lang.ref.WeakReference; public class DnDManagerImpl extends DnDManager implements DnDEvent.DropTargetHighlightingType { private static final Logger LOG = Logger.getInstance("com.intellij.ide.dnd.DnDManager"); static final @NonNls String SOURCE_KEY = "DnD Source"; static final @NonNls String TARGET_KEY = "DnD Target"; public static final Key<Pair<Image, Point>> DRAGGED_IMAGE_KEY = new Key<Pair<Image, Point>>("draggedImage"); private DnDEventImpl myCurrentEvent; private DnDEvent myLastHighlightedEvent; private static DnDTarget NULL_TARGET = new NullTarget(); private WeakReference<DnDTarget> myLastProcessedTarget = new WeakReference<DnDTarget>(NULL_TARGET); private DragSourceContext myCurrentDragContext; private Component myLastProcessedOverComponent; private Point myLastProcessedPoint; private String myLastMessage; private DnDEvent myLastProcessedEvent; private DragGestureListener myDragGestureListener = new MyDragGestureListnener(); private DropTargetListener myDropTargetListener = new MyDropTargetListener(); private static final Image EMPTY_IMAGE = new BufferedImage(1, 1, Transparency.TRANSLUCENT); private Timer myTooltipTimer = new Timer(ToolTipManager.sharedInstance().getInitialDelay(), new ActionListener() { public void actionPerformed(ActionEvent e) { onTimer(); } }); private Runnable myHightlighterShowRequest; private Rectangle myLastHighlightedRec; private int myLastProcessedAction; private Application myApp; public DnDManagerImpl(final Application app) { myApp = app; myTooltipTimer.start(); } public void registerSource(@NotNull final AdvancedDnDSource source) { if (!getApplication().isHeadlessEnvironment()) { final JComponent c = source.getComponent(); registerSource(source, c); final DnDEnabler enabler = new DnDEnabler(source, source); c.putClientProperty(DnDEnabler.KEY, enabler); } } public void registerSource(DnDSource source, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(SOURCE_KEY, source); final DragSource defaultDragSource = DragSource.getDefaultDragSource(); defaultDragSource.createDefaultDragGestureRecognizer(component, DnDConstants.ACTION_COPY_OR_MOVE, myDragGestureListener); } } public void unregisterSource(AdvancedDnDSource source) { final JComponent c = source.getComponent(); if (c != null) { final DnDEnabler enabler = (DnDEnabler)c.getClientProperty(DnDEnabler.KEY); if (enabler != null) { Disposer.dispose(enabler); c.putClientProperty(DnDEnabler.KEY, null); } } unregisterSource(source, c); } public void unregisterSource(DnDSource source, JComponent component) { component.putClientProperty(SOURCE_KEY, null); _dispose(); } private void _dispose() { myLastProcessedOverComponent = null; myCurrentDragContext = null; myCurrentEvent = null; } public void registerTarget(DnDTarget target, JComponent component) { if (!getApplication().isHeadlessEnvironment()) { component.putClientProperty(TARGET_KEY, target); new DropTarget(component, DnDConstants.ACTION_COPY_OR_MOVE, myDropTargetListener); } } public void unregisterTarget(DnDTarget target, JComponent component) { component.putClientProperty(TARGET_KEY, null); _dispose(); } private void updateCurrentEvent(Component aComponentOverDragging, Point aPoint, int nativeAction) { LOG.debug("updateCurrentEvent: " + aComponentOverDragging); if (myCurrentDragContext == null) return; myCurrentEvent.updateAction(getDnDActionForPlatformAction(nativeAction)); myCurrentEvent.setPoint(aPoint); myCurrentEvent.setHandlerComponent(aComponentOverDragging); boolean samePoint = myCurrentEvent.getPoint().equals(myLastProcessedPoint); boolean sameComponent = myCurrentEvent.getCurrentOverComponent().equals(myLastProcessedOverComponent); boolean sameAction = (nativeAction == myLastProcessedAction); LOG.debug("updateCurrentEvent: point:" + aPoint); LOG.debug("updateCurrentEvent: action:" + nativeAction); if (samePoint && sameComponent && sameAction) { return; } DnDTarget target = getTarget(aComponentOverDragging); DnDTarget immediateTarget = target; Component eachParent = aComponentOverDragging; final Pair<Image, Point> pair = myCurrentEvent.getUserData(DRAGGED_IMAGE_KEY); if (pair != null) { target.updateDraggedImage(pair.first, aPoint, pair.second); } LOG.debug("updateCurrentEvent: action:" + nativeAction); while (true) { boolean canGoToParent = update(target); if (myCurrentEvent.isDropPossible()) { if (myCurrentEvent.wasDelegated()) { target = myCurrentEvent.getDelegatedTarget(); } break; } if (!canGoToParent) { break; } eachParent = findAllowedParentComponent(eachParent); if (eachParent == null) { break; } target = getTarget(eachParent); } LOG.debug("updateCurrentEvent: target:" + target); LOG.debug("updateCurrentEvent: immediateTarget:" + immediateTarget); if (!myCurrentEvent.isDropPossible() && !immediateTarget.equals(target)) { update(immediateTarget); } updateCursor(); final Container current = (Container)myCurrentEvent.getCurrentOverComponent(); final Point point = myCurrentEvent.getPointOn(getLayeredPane(current)); Rectangle inPlaceRect = new Rectangle(point.x - 5, point.y - 5, 5, 5); if (!myCurrentEvent.equals(myLastProcessedEvent)) { hideCurrentHighlighter(); } boolean sameTarget = getLastProcessedTarget().equals(target); if (sameTarget) { if (myCurrentEvent.isDropPossible()) { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { if (!Highlighters.isVisibleExcept(TEXT | ERROR_TEXT)) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { if (!myLastProcessedPoint.equals(myCurrentEvent.getPoint())) { hideCurrentHighlighter(); restartTimer(); queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } } else { hideCurrentHighlighter(); getLastProcessedTarget().cleanUpOnLeave(); myCurrentEvent.clearDropHandler(); restartTimer(); if (!myCurrentEvent.isDropPossible()) { queueTooltip(myCurrentEvent, getLayeredPane(current), inPlaceRect); } } myLastProcessedTarget = new WeakReference<DnDTarget>(target); myLastProcessedPoint = myCurrentEvent.getPoint(); myLastProcessedOverComponent = myCurrentEvent.getCurrentOverComponent(); myLastProcessedAction = myCurrentEvent.getAction().getActionId(); myLastProcessedEvent = (DnDEvent)myCurrentEvent.clone(); } private void updateCursor() { Cursor cursor; if (myCurrentEvent.isDropPossible()) { cursor = myCurrentEvent.getCursor(); if (cursor == null) { cursor = myCurrentEvent.getAction().getCursor(); } } else { cursor = myCurrentEvent.getAction().getRejectCursor(); } myCurrentDragContext.setCursor(cursor); } private void restartTimer() { myTooltipTimer.restart(); } private boolean update(DnDTarget target) { LOG.debug("update target:" + target); myCurrentEvent.clearDelegatedTarget(); final boolean canGoToParent = target.update(myCurrentEvent); String message; if (isMessageProvided(myCurrentEvent)) { message = myCurrentEvent.getExpectedDropResult(); } else { message = ""; } //final WindowManager wm = WindowManager.getInstance(); //final StatusBar statusBar = wm.getStatusBar(target.getProject()); //statusBar.setInfo(message); if (myLastMessage != null && !myLastMessage.equals(message)) { hideCurrentHighlighter(); } myLastMessage = message; return canGoToParent; } private static Component findAllowedParentComponent(Component aComponentOverDragging) { Component eachParent = aComponentOverDragging; while (true) { eachParent = eachParent.getParent(); if (eachParent == null) { return null; } final DnDTarget target = getTarget(eachParent); if (target != NULL_TARGET) { return eachParent; } } } private static DnDSource getSource(Component component) { if (component instanceof JComponent) { return (DnDSource)((JComponent)component).getClientProperty(SOURCE_KEY); } return null; } private static DnDTarget getTarget(Component component) { if (component instanceof JComponent) { DnDTarget target = (DnDTarget)((JComponent)component).getClientProperty(TARGET_KEY); if (target != null) return target; } return NULL_TARGET; } void showHighlighter(final Component aComponent, final int aType, final DnDEvent aEvent) { final Rectangle bounds = aComponent.getBounds(); final Container parent = aComponent.getParent(); showHighlighter(parent, aEvent, bounds, aType); } void showHighlighter(final RelativeRectangle rectangle, final int aType, final DnDEvent aEvent) { final JLayeredPane layeredPane = getLayeredPane(rectangle.getPoint().getComponent()); final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, aEvent, bounds, aType); } void showHighlighter(JLayeredPane layeredPane, final RelativeRectangle rectangle, final int aType, final DnDEvent event) { final Rectangle bounds = rectangle.getRectangleOn(layeredPane); showHighlighter(layeredPane, event, bounds, aType); } private boolean isEventBeingHighlighted(DnDEvent event) { return event.equals(getLastHighlightedEvent()); } private void showHighlighter(final Component parent, final DnDEvent aEvent, final Rectangle bounds, final int aType) { final JLayeredPane layeredPane = getLayeredPane(parent); if (layeredPane == null) { return; } if (isEventBeingHighlighted(aEvent)) { if (GeometryUtil.isWithin(myLastHighlightedRec, aEvent.getPointOn(layeredPane))) { return; } } final Rectangle rectangle = SwingUtilities.convertRectangle(parent, bounds, layeredPane); setLastHighlightedEvent((DnDEvent)((DnDEventImpl)aEvent).clone(), rectangle); Highlighters.hide(); Highlighters.show(aType, layeredPane, rectangle, aEvent); if (isMessageProvided(aEvent)) { queueTooltip(aEvent, layeredPane, rectangle); } else { Highlighters.hide(TEXT | ERROR_TEXT); } } private void queueTooltip(final DnDEvent aEvent, final JLayeredPane aLayeredPane, final Rectangle aRectangle) { myHightlighterShowRequest = new Runnable() { public void run() { if (myCurrentEvent != aEvent) return; Highlighters.hide(TEXT | ERROR_TEXT); if (aEvent.isDropPossible()) { Highlighters.show(TEXT, aLayeredPane, aRectangle, aEvent); } else { Highlighters.show(ERROR_TEXT, aLayeredPane, aRectangle, aEvent); } } }; } private static boolean isMessageProvided(final DnDEvent aEvent) { return aEvent.getExpectedDropResult() != null && aEvent.getExpectedDropResult().trim().length() > 0; } void hideCurrentHighlighter() { Highlighters.hide(); myHightlighterShowRequest = null; setLastHighlightedEvent(null, null); } private void onTimer() { if (myHightlighterShowRequest != null) { myHightlighterShowRequest.run(); myHightlighterShowRequest = null; } } private static JLayeredPane getLayeredPane(Component aComponent) { if (aComponent == null) return null; if (aComponent instanceof JLayeredPane) { return (JLayeredPane)aComponent; } if (aComponent instanceof JFrame) { return ((JFrame)aComponent).getRootPane().getLayeredPane(); } if (aComponent instanceof JDialog) { return ((JDialog)aComponent).getRootPane().getLayeredPane(); } final Window window = SwingUtilities.getWindowAncestor(aComponent); if (window instanceof JFrame) { return ((JFrame) window).getRootPane().getLayeredPane(); } else if (window instanceof JDialog) { return ((JDialog) window).getRootPane().getLayeredPane(); } return null; } private DnDTarget getLastProcessedTarget() { return myLastProcessedTarget.get(); } private static class NullTarget implements DnDTarget { public boolean update(DnDEvent aEvent) { aEvent.setDropPossible(false, "You cannot drop anything here"); return false; } public void drop(DnDEvent aEvent) { } public void cleanUpOnLeave() { } public void updateDraggedImage(Image image, Point dropPoint, Point imageOffset) { } } DnDEvent getCurrentEvent() { return myCurrentEvent; } private DnDEvent getLastHighlightedEvent() { return myLastHighlightedEvent; } private void setLastHighlightedEvent(DnDEvent lastHighlightedEvent, Rectangle aRectangle) { myLastHighlightedEvent = lastHighlightedEvent; myLastHighlightedRec = aRectangle; } private void resetCurrentEvent(@NonNls String s) { myCurrentEvent = null; LOG.debug("Reset Current Event: " + s); } private class MyDragGestureListnener implements DragGestureListener { public void dragGestureRecognized(DragGestureEvent dge) { final DnDSource source = getSource(dge.getComponent()); if (source == null) return; DnDAction action = getDnDActionForPlatformAction(dge.getDragAction()); if (source.canStartDragging(action, dge.getDragOrigin())) { if (myCurrentEvent == null) { // Actually, under Linux it is possible to get 2 or more dragGestureRecognized calls for single drag // operation. To reproduce: // 1. Do D-n-D in Styles tree // 2. Make an attempt to do D-n-D in Services tree // 3. Do D-n-D in Styles tree again. LOG.debug("Starting dragging for " + action); hideCurrentHighlighter(); final DnDDragStartBean dnDDragStartBean = source.startDragging(action, dge.getDragOrigin()); myCurrentEvent = new DnDEventImpl(DnDManagerImpl.this, action, dnDDragStartBean.getAttachedObject(), dnDDragStartBean.getPoint()); myCurrentEvent.setOrgPoint(dge.getDragOrigin()); Pair<Image, Point> pair = source.createDraggedImage(action, dge.getDragOrigin()); if (pair == null) { pair = new Pair<Image, Point>(EMPTY_IMAGE, new Point(0, 0)); } if (!DragSource.isDragImageSupported()) { // not all of the platforms supports image dragging (mswin doesn't, for example). myCurrentEvent.putUserData(DRAGGED_IMAGE_KEY, pair); } // mac osx fix: it will draw a border with size of the dragged component if there is no image provided. dge.startDrag(DragSource.DefaultCopyDrop, pair.first, pair.second, myCurrentEvent, new MyDragSourceListener(source)); // check if source is also a target // DnDTarget target = getTarget(dge.getComponent()); // if( target != null ) { // target.update(myCurrentEvent); } } } } private static DnDAction getDnDActionForPlatformAction(int platformAction) { DnDAction action = null; switch (platformAction) { case DnDConstants.ACTION_COPY: action = DnDAction.COPY; break; case DnDConstants.ACTION_MOVE: action = DnDAction.MOVE; break; case DnDConstants.ACTION_LINK: action = DnDAction.LINK; break; default: break; } return action; } private class MyDragSourceListener implements DragSourceListener { private final DnDSource mySource; public MyDragSourceListener(final DnDSource source) { mySource = source; } public void dragEnter(DragSourceDragEvent dsde) { LOG.debug("dragEnter:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dragOver(DragSourceDragEvent dsde) { LOG.debug("dragOver:" + dsde.getDragSourceContext().getComponent()); myCurrentDragContext = dsde.getDragSourceContext(); } public void dropActionChanged(DragSourceDragEvent dsde) { mySource.dropActionChanged(dsde.getGestureModifiers()); } public void dragDropEnd(DragSourceDropEvent dsde) { mySource.dragDropEnd(); getLastProcessedTarget().cleanUpOnLeave(); resetCurrentEvent("dragDropEnd:" + dsde.getDragSourceContext().getComponent()); Highlighters.hide(TEXT | ERROR_TEXT); } public void dragExit(DragSourceEvent dse) { LOG.debug("Stop dragging1"); onDragExit(); } } private class MyDropTargetListener implements DropTargetListener { public void drop(final DropTargetDropEvent dtde) { try { final Component component = dtde.getDropTargetContext().getComponent(); updateCurrentEvent(component, dtde.getLocation(), dtde.getDropAction()); final DnDEventImpl event = myCurrentEvent; if (event != null && event.isDropPossible()) { dtde.acceptDrop(dtde.getDropAction()); // do not wrap this into WriteAction! doDrop(component); if (event.shouldRemoveHighlightings()) { hideCurrentHighlighter(); } dtde.dropComplete(true); } else { dtde.rejectDrop(); } } catch (Throwable e) { LOG.error(e); dtde.rejectDrop(); } finally { resetCurrentEvent("Stop dragging2"); } } private void doDrop(Component component) { if (myCurrentEvent.canHandleDrop()) { myCurrentEvent.handleDrop(); } else { getTarget(component).drop(myCurrentEvent); } } public void dragOver(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } public void dragExit(DropTargetEvent dte) { onDragExit(); } public void dragEnter(DropTargetDragEvent dtde) { } public void dropActionChanged(DropTargetDragEvent dtde) { updateCurrentEvent(dtde.getDropTargetContext().getComponent(), dtde.getLocation(), dtde.getDropAction()); } } private void onDragExit() { if (myCurrentDragContext != null) { myCurrentDragContext.setCursor(null); } getLastProcessedTarget().cleanUpOnLeave(); hideCurrentHighlighter(); myHightlighterShowRequest = null; } private Application getApplication() { return myApp; } }
package com.breadwallet.presenter.fragments; import android.app.Activity; import android.app.AlertDialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.breadwallet.R; import com.breadwallet.BreadWalletApp; import com.breadwallet.presenter.activities.IntroActivity; import com.breadwallet.presenter.activities.MainActivity; import com.breadwallet.presenter.entities.PaymentRequestEntity; import com.breadwallet.presenter.entities.PaymentRequestWrapper; import com.breadwallet.tools.animation.BRAnimator; import com.breadwallet.tools.util.BRConstants; import com.breadwallet.tools.util.BRStringFormatter; import com.breadwallet.tools.manager.SharedPreferencesManager; import com.breadwallet.tools.adapter.CustomPagerAdapter; import com.breadwallet.tools.adapter.MiddleViewAdapter; import com.breadwallet.tools.animation.SpringAnimator; import com.breadwallet.tools.security.KeyStoreManager; import com.breadwallet.tools.security.PassCodeManager; import com.breadwallet.tools.threads.PaymentProtocolPostPaymentTask; import com.breadwallet.wallet.BRWalletManager; import java.util.Locale; public class PasswordDialogFragment extends DialogFragment { private static final String TAG = PasswordDialogFragment.class.getName(); private EditText passcodeEditText; private EditText phraseEditText; private Button cancel; private Button reset; private DialogFragment dialogFragment; private int currentMode = BRConstants.AUTH_MODE_CHECK_PASS; private String tempPassToChange; private boolean firstTime = false; // if false then change; private boolean verifyOnly = false; private TextView title; private TextView digit_1; private TextView digit_2; private TextView digit_3; private TextView digit_4; private PaymentRequestEntity request; private PaymentRequestWrapper paymentRequest; private TextView info; private TextWatcher textWatcher; private String prevPass; private String message; private TextView description; private int mode = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(STYLE_NO_TITLE, 0); } @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_password_dialog, container); dialogFragment = this; passcodeEditText = (EditText) view.findViewById(R.id.edit_passcode); phraseEditText = (EditText) view.findViewById(R.id.edit_phrase); cancel = (Button) view.findViewById(R.id.button_password_cancel); reset = (Button) view.findViewById(R.id.button_password_reset); title = (TextView) view.findViewById(R.id.passcode_dialog_title); info = (TextView) view.findViewById(R.id.password_info_text); description = (TextView) view.findViewById(R.id.passcode_dialog_description); if (message != null) description.setText(message); digit_1 = (TextView) view.findViewById(R.id.passcode_digit1); digit_2 = (TextView) view.findViewById(R.id.passcode_digit2); digit_3 = (TextView) view.findViewById(R.id.passcode_digit3); digit_4 = (TextView) view.findViewById(R.id.passcode_digit4); prevPass = ""; clearDigits(); final InputMethodManager keyboard = (InputMethodManager) getActivity(). getSystemService(Context.INPUT_METHOD_SERVICE); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getDialog().cancel(); passcodeEditText.setText(""); keyboard.hideSoftInputFromWindow(cancel.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); if (!MainActivity.scanResultFragmentOn && mode == BRConstants.AUTH_FOR_PAY && request.isAmountRequested) { FragmentScanResult.address = request.addresses[0]; new AlertDialog.Builder(getActivity()) .setTitle(getString(R.string.payment_info)) .setMessage(R.string.change_payment_amount) .setPositiveButton(R.string.change, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { BRAnimator.animateScanResultFragment(); } }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); FragmentScanResult.address = null; } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } } }); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (phraseEditText == null) return; (new Handler()).postDelayed(new Runnable() { public void run() { phraseEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0)); phraseEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0)); } }, 100); if (phraseEditText.getVisibility() == View.GONE) { phraseEditText.setVisibility(View.VISIBLE); title.setText(R.string.recovery_title); description.setText(""); info.setVisibility(View.GONE); } else { if (!phraseEditText.getText().toString().isEmpty() && KeyStoreManager.phraseIsValid(phraseEditText.getText().toString().toLowerCase(), getActivity())) { KeyStoreManager.putFailCount(0, getActivity()); KeyStoreManager.putFailTimeStamp(0, getActivity()); validatePassCode(String.valueOf(KeyStoreManager.getPassCode(getActivity()))); getDialog().dismiss(); } else { final String tmpTitle = title.getText().toString(); title.setText(R.string.phrase_no_match); new Handler().postDelayed(new Runnable() { @Override public void run() { title.setText(tmpTitle); } }, 3000); } } } }); int failCount = KeyStoreManager.getFailCount(getActivity()); long secureTime = SharedPreferencesManager.getSecureTime(getActivity()); long failTimestamp = KeyStoreManager.getFailTimeStamp(getActivity()); if (secureTime == 0) secureTime = System.currentTimeMillis() / 1000; updateInfoText(); if (secureTime < failTimestamp + Math.pow(6, failCount - 3) * 60.0) { setWalletDisabled(); return view; } view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { keyboard.showSoftInput(passcodeEditText, 0); } }); title.setText(getResources().getString(R.string.enter_old_passcode)); getDialog().getWindow().setBackgroundDrawableResource(R.drawable.rounded_dialog); if (firstTime) { cancel.setClickable(false); cancel.setVisibility(View.GONE); title.setText(R.string.choose_new_passcode); currentMode = BRConstants.AUTH_MODE_NEW_PASS; } if (verifyOnly) { title.setText(R.string.enter_passcode); } textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { addRemoveDigit(s.length()); if (s.length() == 4) validatePassCode(s); } @Override public void afterTextChanged(Editable s) { } }; passcodeEditText.addTextChangedListener(textWatcher); getDialog().setCanceledOnTouchOutside(false); return view; } @Override public void onResume() { super.onResume(); passcodeEditText.setText(""); final Activity app = getActivity(); if (app != null) { passcodeEditText.post( new Runnable() { public void run() { InputMethodManager inputMethodManager = (InputMethodManager) app.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow(passcodeEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); passcodeEditText.requestFocus(); } }); } } @Override public void onPause() { super.onPause(); InputMethodManager keyboard = (InputMethodManager) getActivity(). getSystemService(Context.INPUT_METHOD_SERVICE); EditText editText = CustomPagerAdapter.adapter. mainFragment.addressEditText; if (CustomPagerAdapter.adapter != null && editText != null) keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0); // BreadWalletApp.canceled = true; } public void setFirstTimeTrue() { firstTime = true; verifyOnly = false; } public void setVerifyOnlyTrue() { verifyOnly = true; firstTime = false; } private boolean validatePassCode(CharSequence s) { PassCodeManager passCodeManager = PassCodeManager.getInstance(); //Set and confirm the new passcode if (firstTime) { switch (currentMode) { case BRConstants.AUTH_MODE_NEW_PASS: tempPassToChange = s.toString(); currentMode = BRConstants.AUTH_MODE_CONFIRM_PASS; title.setText(getResources().getString(R.string.verify_passcode)); passcodeEditText.setText(""); break; case BRConstants.AUTH_MODE_CONFIRM_PASS: String passToCheck = s.toString(); if (passToCheck.equals(tempPassToChange)) { passCodeManager.setPassCode(tempPassToChange, getActivity()); tempPassToChange = ""; try { getDialog().dismiss(); } catch (Exception e) { e.printStackTrace(); } String tmp = BRStringFormatter.getCurrentBalanceText(getActivity()); MiddleViewAdapter.resetMiddleView(getActivity(), tmp); ((BreadWalletApp) getActivity().getApplicationContext()).setUnlocked(true); InputMethodManager keyboard = (InputMethodManager) getActivity(). getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.hideSoftInputFromWindow(cancel.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); currentMode = BRConstants.AUTH_MODE_CHECK_PASS; } else { SpringAnimator.showAnimation(dialogFragment.getView()); passcodeEditText.setText(""); currentMode = BRConstants.AUTH_MODE_NEW_PASS; title.setText(getResources().getString(R.string.choose_new_passcode)); } break; } // verify the passcode } else if (verifyOnly) { //assume the passcode is wrong all the time if (!prevPass.equals(s.toString())) { KeyStoreManager.putFailCount(KeyStoreManager.getFailCount(getActivity()) + 1, getActivity()); } prevPass = s.toString(); if (KeyStoreManager.getFailCount(getActivity()) >= 3) setWalletDisabled(); if (passCodeManager.checkAuth(s.toString(), getActivity())) { //reset the passcode after successful attempt KeyStoreManager.putFailCount(0, getActivity()); // BreadWalletApp.canceled = true; getDialog().cancel(); long totalSpent = BRWalletManager.getInstance(getActivity()).getTotalSent(); long spendLimit = totalSpent + PassCodeManager.getInstance().getLimit(getActivity()) + (request == null ? 0 : request.amount); KeyStoreManager.putSpendLimit(spendLimit, getActivity()); Log.e(TAG, "Setting the new limit: " + spendLimit + ", totalSpent was: " + totalSpent); ((BreadWalletApp) getActivity().getApplicationContext()).setUnlocked(true); FragmentSettingsAll.refreshUI(getActivity()); MiddleViewAdapter.resetMiddleView(getActivity(), null); ((BreadWalletApp) getActivity().getApplicationContext()).allowKeyStoreAccessForSeconds(); getDialog().dismiss(); passcodeEditText.setText(""); Log.e(TAG, "mode: " + mode + " request: " + request); if (mode == BRConstants.AUTH_FOR_PHRASE) { BRAnimator.animateSlideToLeft((MainActivity) getActivity(), new FragmentRecoveryPhrase(), new FragmentSettings()); } else if (mode == BRConstants.AUTH_FOR_LIMIT) { BRAnimator.animateSlideToLeft((MainActivity) getActivity(), new FragmentSpendLimit(), new FragmentSettings()); } else if (mode == BRConstants.AUTH_FOR_PAY && request != null) { BRWalletManager walletManager = BRWalletManager.getInstance(getActivity()); String seed = KeyStoreManager.getKeyStorePhrase(getActivity(), BRConstants.PAY_REQUEST_CODE); if (seed != null && !seed.isEmpty()) { boolean success; if (request.serializedTx != null) { success = walletManager.publishSerializedTransaction(request.serializedTx, seed); request.serializedTx = null; } else { success = walletManager.pay(request.addresses[0], (request.amount), seed); } if (!success) { ((BreadWalletApp) getActivity().getApplication()).showCustomToast(getActivity(), "Failed to send", MainActivity.screenParametersPoint.y / 2, Toast.LENGTH_LONG, 0); return false; } } else { return false; } seed = null; BRAnimator.hideScanResultFragment(); } else if (mode == BRConstants.AUTH_FOR_PAYMENT_PROTOCOL && paymentRequest != null) { if (paymentRequest.paymentURL == null || paymentRequest.paymentURL.isEmpty()) return false; new PaymentProtocolPostPaymentTask(paymentRequest).execute(); } } else { SpringAnimator.showAnimation(dialogFragment.getView()); passcodeEditText.setText(""); } } else { switch (currentMode) { case BRConstants.AUTH_MODE_CHECK_PASS: if (passCodeManager.checkAuth(s.toString(), getActivity())) { currentMode = BRConstants.AUTH_MODE_NEW_PASS; title.setText(getResources().getString(R.string.choose_new_passcode)); passcodeEditText.setText(""); } else { SpringAnimator.showAnimation(dialogFragment.getView()); passcodeEditText.setText(""); } break; case BRConstants.AUTH_MODE_NEW_PASS: if (s.length() > 3 && s.length() < 12) { tempPassToChange = s.toString(); currentMode = BRConstants.AUTH_MODE_CONFIRM_PASS; title.setText(getResources().getString(R.string.verify_passcode)); passcodeEditText.setText(""); } else { SpringAnimator.showAnimation(dialogFragment.getView()); passcodeEditText.setText(""); } break; case BRConstants.AUTH_MODE_CONFIRM_PASS: String passToCheck = s.toString(); if (passToCheck.equals(tempPassToChange)) { passCodeManager.setPassCode(tempPassToChange, getActivity()); tempPassToChange = ""; getDialog().cancel(); String tmp = BRStringFormatter.getCurrentBalanceText(getActivity()); MiddleViewAdapter.resetMiddleView(getActivity(), tmp); ((BreadWalletApp) getActivity().getApplicationContext()).setUnlocked(true); InputMethodManager keyboard = (InputMethodManager) getActivity(). getSystemService(Context.INPUT_METHOD_SERVICE); keyboard.hideSoftInputFromWindow(cancel.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY); currentMode = BRConstants.AUTH_MODE_CHECK_PASS; } else { SpringAnimator.showAnimation(dialogFragment.getView()); passcodeEditText.setText(""); currentMode = BRConstants.AUTH_MODE_NEW_PASS; title.setText(getResources().getString(R.string.choose_new_passcode)); } break; } } return false; } private void updateInfoText() { int failCount = KeyStoreManager.getFailCount(getActivity()); int attemptsRemaining = 8 - failCount; if (attemptsRemaining <= 0) { BRWalletManager m = BRWalletManager.getInstance(getActivity()); m.wipeKeyStore(); m.wipeWalletButKeystore(getActivity()); startIntroActivity(); BRAnimator.resetFragmentAnimator(); } if (failCount >= 3) { info.setVisibility(View.VISIBLE); info.setText(String.format(Locale.getDefault(), getActivity().getString(R.string.attempts_remaining), attemptsRemaining < 0 ? 0 : attemptsRemaining)); } } private void setWalletDisabled() { int failCount = KeyStoreManager.getFailCount(getActivity()); long secureTime = SharedPreferencesManager.getSecureTime(getActivity()); long failTimestamp = KeyStoreManager.getFailTimeStamp(getActivity()); double waitTime = (failTimestamp + Math.pow(6, failCount - 3) * 60.0 - secureTime) / 60.0; title.setText(R.string.wallet_disabled); description.setText(""); passcodeEditText.setVisibility(View.GONE); info.setVisibility(View.VISIBLE); // Get the Resources Resources res = getResources(); String tryAgain = res.getQuantityString(R.plurals.try_again, (int) waitTime); String message = String.format(tryAgain, (int) waitTime); info.setText(message); digit_1.setVisibility(View.GONE); digit_2.setVisibility(View.GONE); digit_3.setVisibility(View.GONE); digit_4.setVisibility(View.GONE); getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); passcodeEditText.removeTextChangedListener(textWatcher); reset.setVisibility(View.VISIBLE); } public void setPaymentRequestEntity(PaymentRequestEntity requestEntity, PaymentRequestWrapper paymentRequest) { request = requestEntity; this.paymentRequest = paymentRequest; } public void setMode(int mode) { this.mode = mode; } private void addRemoveDigit(int digits) { if (digit_1 == null) return; digit_1.setText(digits >= 1 ? BRConstants.LITTLE_CIRCLE : "-"); digit_2.setText(digits >= 2 ? BRConstants.LITTLE_CIRCLE : "-"); digit_3.setText(digits >= 3 ? BRConstants.LITTLE_CIRCLE : "-"); digit_4.setText(digits >= 4 ? BRConstants.LITTLE_CIRCLE : "-"); } private void clearDigits() { if (digit_1 == null) return; digit_1.setText("-"); digit_2.setText("-"); digit_3.setText("-"); digit_4.setText("-"); } private void startIntroActivity() { Intent intent; intent = new Intent(getActivity(), IntroActivity.class); startActivity(intent); if (!getActivity().isDestroyed()) { getActivity().finish(); } } public void setMessage(String message) { this.message = message; } }
package com.nestedworld.nestedworld.fragment.profil; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.nestedworld.nestedworld.R; import com.nestedworld.nestedworld.activity.launch.LaunchActivity; import com.nestedworld.nestedworld.api.implementation.NestedWorldApi; import com.nestedworld.nestedworld.api.models.User; import com.nestedworld.nestedworld.api.models.apiResponse.users.auth.LogoutResponse; import com.nestedworld.nestedworld.authenticator.UserManager; import com.nestedworld.nestedworld.fragment.base.BaseFragment; import butterknife.Bind; import butterknife.OnClick; import retrofit.Response; import retrofit.Retrofit; /** * A placeholder fragment containing a simple view. */ public class ProfilFragment extends BaseFragment { public final static String FRAGMENT_NAME = ProfilFragment.class.getSimpleName(); @Bind(R.id.textView_gender) TextView textViewGender; @Bind(R.id.textView_pseudo) TextView textViewPseudo; @Bind(R.id.textView_birthDate) TextView textViewBirthDate; @Bind(R.id.textView_city) TextView textViewCity; @Bind(R.id.textView_registeredAt) TextView textViewRegisteredAt; @Bind(R.id.textView_email) TextView textViewEmail; public static void load(@NonNull final FragmentManager fragmentManager, final boolean toBackStack) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, new ProfilFragment()); if (toBackStack) { fragmentTransaction.addToBackStack(FRAGMENT_NAME); } fragmentTransaction.commit(); } /* ** Life cycle */ @Override protected int getLayoutResource() { return R.layout.fragment_acton_profil; } @Override protected void init(View rootView, Bundle savedInstanceState) { /*We retrieve the userData as the string and we decode the string*/ if (mContext != null) { final User user = UserManager.get(mContext).getCurrentUser(mContext); if (user != null) { /*We display some information from the decoded user*/ textViewGender.setText(user.gender); textViewPseudo.setText(user.pseudo); textViewBirthDate.setText(user.birth_date); textViewCity.setText(user.city); textViewRegisteredAt.setText(user.registered_at); textViewEmail.setText(user.email); } } } /* ** Butterknife */ @OnClick(R.id.button_logout) public void logout() { if (mContext == null) return; NestedWorldApi.getInstance(mContext).logout( new com.nestedworld.nestedworld.api.callback.Callback<LogoutResponse>() { @Override public void onSuccess(Response<LogoutResponse> response, Retrofit retrofit) { } @Override public void onError(@NonNull KIND errorKind, @Nullable Response<LogoutResponse> response) { } }); //remove user UserManager.get(mContext).deleteCurrentAccount(mContext); //avoid leek with the static instance NestedWorldApi.reset(); //go to launch screen & kill the current context startActivity(LaunchActivity.class); ((AppCompatActivity) mContext).finish(); } }
package com.nestedworld.nestedworld.ui.fight.battle; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.nestedworld.nestedworld.R; import com.nestedworld.nestedworld.customView.drawingGestureView.DrawingGestureView; import com.nestedworld.nestedworld.customView.drawingGestureView.listener.DrawingGestureListener; import com.nestedworld.nestedworld.customView.drawingGestureView.listener.OnFinishMoveListener; import com.nestedworld.nestedworld.database.models.Attack; import com.nestedworld.nestedworld.database.models.Monster; import com.nestedworld.nestedworld.database.models.UserMonster; import com.nestedworld.nestedworld.events.socket.combat.OnAttackReceiveEvent; import com.nestedworld.nestedworld.events.socket.combat.OnMonsterKoEvent; import com.nestedworld.nestedworld.helpers.log.LogHelper; import com.nestedworld.nestedworld.helpers.service.ServiceHelper; import com.nestedworld.nestedworld.network.http.implementation.NestedWorldHttpApi; import com.nestedworld.nestedworld.network.http.models.response.monsters.MonsterAttackResponse; import com.nestedworld.nestedworld.network.socket.implementation.NestedWorldSocketAPI; import com.nestedworld.nestedworld.network.socket.implementation.SocketMessageType; import com.nestedworld.nestedworld.network.socket.models.message.combat.AttackReceiveMessage; import com.nestedworld.nestedworld.network.socket.models.message.combat.MonsterKoMessage; import com.nestedworld.nestedworld.network.socket.models.message.combat.StartMessage; import com.nestedworld.nestedworld.network.socket.models.request.combat.SendAttackRequest; import com.nestedworld.nestedworld.service.SocketService; import com.nestedworld.nestedworld.ui.base.BaseAppCompatActivity; import com.nestedworld.nestedworld.ui.base.BaseFragment; import com.rey.material.widget.ProgressView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.BindViews; public class BattleFragment extends BaseFragment { /* ** Butterknife binding */ @BindView(R.id.progressView) ProgressView progressView; @BindView(R.id.layout_player) View layoutPlayer; @BindView(R.id.layout_opponent) View layoutOpponent; @BindViews({ R.id.imageView_top, R.id.imageView_top_right, R.id.imageView_bottom_right, R.id.imageView_bottom, R.id.imageView_bottom_left, R.id.imageView_top_left}) List<ImageView> mTitles; /* ** Private field */ private String mUserGestureInput = ""; private DrawingGestureView mDrawingGestureView; private StartMessage mStartMessage = null; private List<UserMonster> mTeam = null; private final Map<UserMonster, ArrayList<MonsterAttackResponse.MonsterAttack>> mTeamAttack = new HashMap<>(); private final OnFinishMoveListener mOnFinishMoveListener = new OnFinishMoveListener() { @Override public void onFinish() { sendAttack(); } }; private final DrawingGestureListener mDrawingGestureListener = new DrawingGestureListener() { @Override public void onTouch(int tileId) { switch (tileId) { case R.id.imageView_top: mUserGestureInput += "1"; break; case R.id.imageView_top_right: mUserGestureInput += "2"; break; case R.id.imageView_bottom_right: mUserGestureInput += "3"; break; case R.id.imageView_bottom: mUserGestureInput += "4"; break; case R.id.imageView_bottom_left: mUserGestureInput += "5"; break; case R.id.imageView_top_left: mUserGestureInput += "6"; break; default: break; } } }; private UserMonster mCurrentUserMonster; /* ** Public method */ public static void load(@NonNull final FragmentManager fragmentManager, @NonNull final StartMessage startMessage, @NonNull final List<UserMonster> selectedMonster) { BattleFragment fightFragment = new BattleFragment(); fightFragment.setStartMessage(startMessage); fightFragment.setTeam(selectedMonster); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, fightFragment); fragmentTransaction.commit(); } public void setStartMessage(@NonNull final StartMessage startMessage) { mStartMessage = startMessage; } public void setTeam(@NonNull final List<UserMonster> team) { mTeam = team; } /* ** Life cycle */ @Override protected int getLayoutResource() { return R.layout.fragment_fight_battle; } @Override protected void init(@NonNull final View rootView, @Nullable Bundle savedInstanceState) { if (mTeam == null || mStartMessage == null) { throw new IllegalArgumentException("You should call setStartMessage() and setTeam() before binding the fragment"); } //start loading animation progressView.start(); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } /*Hide action bar*/ setupActionBar(); /*Init field*/ mCurrentUserMonster = mTeam.get(0); /*populate the view*/ setupEnvironment(); setupOpponentInfos(mStartMessage.opponent); setupPlayerInfos(mStartMessage.user); /*Init the gestureListener*/ initDrawingGestureView(rootView); /*Load pre-requisite*/ new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { /*Retrieve mTeams attacks (and populate mTeamAttack) */ retrieveMonstersAttacks(); return null; } @Override protected void onPostExecute(Void aVoid) { //Check if fragment hasn't been detach if (mContext == null) { return; } //Enable drawingGestureView (allow user to send attack) enableDrawingGestureView(true); //Stop loading animation progressView.stop(); } }.execute(); } @Override public void onDestroyView() { super.onDestroyView(); if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } /* ** EventBus */ @Subscribe public void onAttackReceive(OnAttackReceiveEvent event) { AttackReceiveMessage message = event.getMessage(); //TODO parse message } @Subscribe public void onMonsterKo(OnMonsterKoEvent event) { MonsterKoMessage monsterKoMessage = event.getMessage(); //TODO parse message } /* ** Private method */ private void setupActionBar() { //Check if fragment hasn't been detach if (mContext != null) { /*Update toolbar title*/ ActionBar actionBar = ((AppCompatActivity) mContext).getSupportActionBar(); if (actionBar != null) { actionBar.hide(); } } } private void setupEnvironment() { //TODO parse mStartMessage.env and set background switch (mStartMessage.env) { case "city": break; default: break; } } private void initDrawingGestureView(@NonNull final View rootView) { //Check if fragment hasn't been detach if (mContext == null) { return; } /*Create and init the drawingGestureView*/ mDrawingGestureView = new DrawingGestureView(mContext); mDrawingGestureView.setEnabled(false); mDrawingGestureView.setTiles(mTitles); /* ** We don't add listener into the gestureView now * We'll add the listener after the pre-requisite loading */ /*Add the custom view under the rootView*/ ((RelativeLayout) rootView.findViewById(R.id.layout_fight_body)).addView(mDrawingGestureView); } private void setupOpponentInfos(@NonNull final StartMessage.Opponent opponent) { //Check if fragment hasn't been detach if (mContext == null) { return; } //Retrieve his monster StartMessage.PlayerMonster monster = opponent.monster; //Init monster list RecyclerView monstersList = (RecyclerView) layoutOpponent.findViewById(R.id.listview_opponentMonster); monstersList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); //Populate monster list BattleMonsterAdapter battleMonsterAdapter = new BattleMonsterAdapter(); battleMonsterAdapter.add(opponent.monster.infos()); for (int i = 1; i < opponent.monsterCount; i++) { battleMonsterAdapter.add(null); } monstersList.setAdapter(battleMonsterAdapter); //Populate opponent monster infos with his current monster updateMonsterContainer(layoutOpponent, monster); } private void setupPlayerInfos(@NonNull final StartMessage.Player player) { //Check if fragment hasn't been detach if (mContext == null) { return; } //Init player monster list RecyclerView monstersList = (RecyclerView) layoutPlayer.findViewById(R.id.listview_playerMonster); monstersList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)); //Populate player monster list BattleMonsterAdapter battleMonsterAdapter = new BattleMonsterAdapter(); for (int i = 0; i < mTeam.size(); i++) { battleMonsterAdapter.add(mTeam.get(i).info()); } monstersList.setAdapter(battleMonsterAdapter); //Populate player monster infos with his currentMonster updateMonsterContainer(layoutPlayer, player.monster); } private void updateMonsterContainer(@NonNull final View container, @NonNull final StartMessage.PlayerMonster monster) { //Retrieve widget TextView monsterLvl = (TextView) container.findViewById(R.id.textview_monster_lvl); TextView monsterName = (TextView) container.findViewById(R.id.textview_monster_name); ImageView monsterPicture = (ImageView) container.findViewById(R.id.imageView_monster); ProgressBar progressBarMonsterHp = (ProgressBar) container.findViewById(R.id.progressBar_MonsterLife); //Populate widget monsterName.setText(monster.name); monsterLvl.setText(String.format(getString(R.string.combat_msg_monster_lvl), monster.level)); progressBarMonsterHp.setMax(monster.hp); progressBarMonsterHp.setProgress(monster.hp); //Populate monster sprite Monster monsterInfos = monster.infos(); if (monsterInfos != null) { Glide.with(mContext) .load(monsterInfos.sprite) .placeholder(R.drawable.default_monster) .error(R.drawable.default_monster) .centerCrop() .into(monsterPicture); } } private void enableDrawingGestureView(final boolean enable) { if (enable) { mDrawingGestureView.setEnabled(true); mDrawingGestureView.setOnFinishMoveListener(mOnFinishMoveListener); mDrawingGestureView.setOnTileTouchListener(mDrawingGestureListener); } else { mDrawingGestureView.setEnabled(false); mDrawingGestureView.setOnFinishMoveListener(null); mDrawingGestureView.setOnTileTouchListener(null); } } private void sendAttack() { //check if fragment hasn't been detach if (mContext == null) { return; } //Start loading animation and disable drawingGesture view (prevent multiple attack sending) progressView.start(); enableDrawingGestureView(false); //Retrieve and clear user gesture Attack.AttackType attackTypeWanted = gestureToAttackType(mUserGestureInput); mUserGestureInput = ""; //Parse user gesture switch (attackTypeWanted) { case UNKNOWN: //Unknow attack, display error message Toast.makeText(mContext, "Unknown attack type", Toast.LENGTH_SHORT).show(); //Stop loading animation and re-enable drawingGestureView progressView.stop(); enableDrawingGestureView(true); return; case OBJECT_USE: //Feature not supported yet, display error message Toast.makeText(mContext, "Feature incoming", Toast.LENGTH_SHORT).show(); //Stop loading animation and re-enable drawingGestureView progressView.stop(); enableDrawingGestureView(true); return; default: sendAttackRequest(attackTypeWanted); } } private void sendAttackRequest(@NonNull final Attack.AttackType attackTypeWanted) { //Check if fragment hasn't been detach if (mContext == null) { return; } //Check if the current monster has an attack of the wanted type final Attack attack = getCurrentMonsterAttackByType(attackTypeWanted); if (attack == null) { //Current monster don't have any attack of the wantend type, just display error message Toast.makeText(mContext, "Your monster didn't have this kind of attack", Toast.LENGTH_SHORT).show(); //Stop loading animation and re-enable drawingGestureView progressView.stop(); enableDrawingGestureView(true); return; } //Current monster have an attack with the wanted type //We bind this fragment to the socketService for sending the attackRequest ServiceHelper.bindToSocketService(mContext, new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //Service connected, retrieving socketApi instance NestedWorldSocketAPI nestedWorldSocketAPI = ((SocketService.LocalBinder) service).getService().getApiInstance(); if (nestedWorldSocketAPI != null) { //Sending request SendAttackRequest data = new SendAttackRequest(mCurrentUserMonster.fkmonster, attack.attack_id); nestedWorldSocketAPI.sendRequest(data, SocketMessageType.MessageKind.TYPE_COMBAT_SEND_ATTACK); } } @Override public void onServiceDisconnected(ComponentName name) { //Cannot send attack (api not available) //Display error message Toast.makeText(mContext, R.string.combat_msg_send_atk_failed, Toast.LENGTH_LONG).show(); //Stop loading animation and re-enable drawingGestureView progressView.stop(); enableDrawingGestureView(true); } }); } @Nullable private Attack getCurrentMonsterAttackByType(@NonNull final Attack.AttackType attackTypeWanted) { //Parse currentMonster.attack for finding an attack of the given type ArrayList<MonsterAttackResponse.MonsterAttack> currentMonsterAttack = mTeamAttack.get(mCurrentUserMonster); for (MonsterAttackResponse.MonsterAttack monsterAttack : currentMonsterAttack) { if (monsterAttack.infos.getType() == attackTypeWanted) { return monsterAttack.infos; } } return null; } private void retrieveMonstersAttacks() { //Check if fragment hasn't been detach if (mContext == null) { return; } NestedWorldHttpApi nestedWorldHttpApi = NestedWorldHttpApi.getInstance(mContext); //Loop over every team member for retrieving his attacks for (int i = 0; i < mTeam.size(); i++) { LogHelper.d(TAG, "Retrieve attacks (task: " + i + ")"); //Get current monster information final UserMonster userMonster = mTeam.get(i); final Monster userMonsterInfo = userMonster.info(); if (userMonsterInfo == null) { throw new IllegalArgumentException("UserMonter not link to any monster"); } try { //Retrieve the current monster attack ArrayList<MonsterAttackResponse.MonsterAttack> attacks = nestedWorldHttpApi.getMonsterAttack(userMonsterInfo.monster_id).execute().body().attacks; //Link attacks to his monster mTeamAttack.put(userMonster, attacks); } catch (IOException e) { e.printStackTrace(); } } } /* ** Utils */ @NonNull private static Attack.AttackType gestureToAttackType(@NonNull final String gestureInput) { LogHelper.d(BattleFragment.class.getSimpleName(), "gestureToAttackType > gestureInput=" + gestureInput); Attack.AttackType attackType; switch (gestureInput) { case "41": attackType = Attack.AttackType.ATTACK; break; case "62": attackType = Attack.AttackType.DEFENSE; break; case "456123": attackType = Attack.AttackType.ATTACK_SP; break; case "432165": attackType = Attack.AttackType.DEFENSE_SP; break; case "6253": attackType = Attack.AttackType.OBJECT_USE; break; default: attackType = Attack.AttackType.UNKNOWN; } return attackType; } }
package com.axelor.apps.base.db.repo; import com.axelor.apps.base.db.IAdministration; import com.axelor.apps.base.db.Partner; import com.axelor.apps.base.exceptions.IExceptionMessage; import com.axelor.apps.base.service.administration.SequenceService; import com.axelor.db.JPA; import com.axelor.exception.AxelorException; import com.axelor.exception.db.IException; import com.axelor.i18n.I18n; import com.axelor.inject.Beans; public class PartnerBaseRepository extends PartnerRepository { @Override public Partner save(Partner partner) { try { if (partner.getPartnerSeq() == null){ String seq = Beans.get(SequenceService.class).getSequenceNumber(IAdministration.PARTNER); if (seq == null) throw new AxelorException(I18n.get(IExceptionMessage.PARTNER_1), IException.CONFIGURATION_ERROR); partner.setPartnerSeq(seq); } return super.save(partner); } catch (Exception e) { JPA.em().getTransaction().rollback(); e.printStackTrace(); } return null; } }
package org.intermine.bio.postprocess; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; import org.intermine.bio.util.BioQueries; import org.intermine.model.bio.Chromosome; import org.intermine.model.bio.DataSet; import org.intermine.model.bio.DataSource; import org.intermine.model.bio.Gene; import org.intermine.model.bio.GeneFlankingRegion; import org.intermine.model.bio.Location; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.util.DynamicUtil; /** * Create features to represent flanking regions of configurable distance either side of gene * featues. These will be used in overlap queries. * @author rns * */ public class CreateFlankingRegions { private ObjectStoreWriter osw = null; private ObjectStore os; private DataSet dataSet; private DataSource dataSource; private Map<Integer, Chromosome> chrs = new HashMap<Integer, Chromosome>(); /** * The sizes in kb of flanking regions to create. */ private static double[] distances = new double[] {0.5, 1, 2, 5, 10}; /** * The values strings for up/down stream from a gene. */ private static String[] directions = new String[] {"upstream", "downstream"}; private static final Logger LOG = Logger.getLogger(CreateFlankingRegions.class); /** * Create a new CreateFlankingRegions object that will operate on the given * ObjectStoreWriter. * * @param osw * the ObjectStoreWriter to use when creating/changing objects */ public CreateFlankingRegions(ObjectStoreWriter osw) { this.osw = osw; this.os = osw.getObjectStore(); dataSource = (DataSource) DynamicUtil.createObject(Collections .singleton(DataSource.class)); dataSource.setName("modMine"); try { dataSource = (DataSource) os.getObjectByExample(dataSource, Collections.singleton("name")); } catch (ObjectStoreException e) { throw new RuntimeException( "unable to fetch modMine DataSource object", e); } } /** * Iterate over genes in database and create flanking regions. * * @throws ObjectStoreException * if there is an ObjectStore problem */ public void createFlankingFeatures() throws ObjectStoreException { Results results = BioQueries.findLocationAndObjects(os, Chromosome.class, Gene.class, false, false, 500); dataSet = (DataSet) DynamicUtil.createObject(Collections .singleton(DataSet.class)); dataSet.setTitle("modMine gene flanking regions"); dataSet.setDescription("Gene flanking regions generated by modMine"); dataSet.setVersion("" + new Date()); // current time and date dataSet.setUrl("http://intermine.modencode.org"); dataSet.setDataSource(dataSource); Iterator resIter = results.iterator(); int count = 0; osw.beginTransaction(); while (resIter.hasNext()) { ResultsRow rr = (ResultsRow) resIter.next(); Integer chrId = (Integer) rr.get(0); Gene gene = (Gene) rr.get(1); Location loc = (Location) rr.get(2); createAndStoreFlankingRegion(getChromosome(chrId), loc, gene); if ((count % 1000) == 0) { LOG.info("Created flankning regions for " + count + " genes."); } count++; } osw.store(dataSet); osw.commitTransaction(); } private void createAndStoreFlankingRegion(Chromosome chr, Location geneLoc, Gene gene) throws ObjectStoreException { for (double distance : distances) { for (String direction : directions) { String strand = geneLoc.getStrand(); // TODO what do we do if strand not set? int geneStart = geneLoc.getStart().intValue(); int geneEnd = geneLoc.getEnd().intValue(); int chrLength = chr.getLength().intValue(); // gene touches a chromosome end so there isn't a flanking region if ((geneStart <= 1) || (geneEnd >= chrLength)) { continue; } GeneFlankingRegion region = (GeneFlankingRegion) DynamicUtil .createObject(Collections.singleton(GeneFlankingRegion.class)); Location location = (Location) DynamicUtil .createObject(Collections.singleton(Location.class)); region.setDistance("" + distance + "kb"); region.setDirection(direction); region.setGene(gene); region.setChromosome(chr); region.setChromosomeLocation(location); region.setOrganism(gene.getOrganism()); region.setPrimaryIdentifier(gene.getPrimaryIdentifier() + " " + distance + "kb " + direction); // this should be some clever algorithm int start, end; if (direction.equals("upstream") && strand.equals("1")) { start = geneStart - (int) Math.round(distance * 1000); end = geneStart - 1; } else if (direction.equals("upstream") && strand.equals("-1")) { start = geneEnd + 1; end = geneEnd + (int) Math.round(distance * 1000); } else if (direction.equals("downstream") && strand.equals("1")) { start = geneEnd + 1; end = geneEnd + (int) Math.round(distance * 1000); } else { // direction.equals("downstream") && strand.equals("-1") start = geneStart - (int) Math.round(distance * 1000); end = geneStart - 1; } // if the region hangs off the start or end of a chromosome set it to finish // at the end of the chromosome location.setStart(Math.max(start, 1)); location.setEnd(Math.min(end, chr.getLength())); location.setStrand(strand); location.setObject(chr); location.setSubject(region); region.setLength(new Integer((location.getEnd() - location.getStart()) + 1)); osw.store(location); osw.store(region); } } } private Chromosome getChromosome(Integer chrId) throws ObjectStoreException { Chromosome chr = chrs.get(chrId); if (chr == null) { chr = (Chromosome) os.getObjectById(chrId, Chromosome.class); chrs.put(chrId, chr); } return chr; } }
package org.intermine.bio.web.displayer; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.intermine.api.InterMineAPI; import org.intermine.api.query.PathQueryExecutor; import org.intermine.api.results.ExportResultsIterator; import org.intermine.api.results.ResultElement; import org.intermine.metadata.Model; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStoreException; import org.intermine.pathquery.Constraints; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.PathQuery; import org.intermine.web.displayer.ReportDisplayer; import org.intermine.web.logic.config.ReportDisplayerConfig; import org.intermine.web.logic.results.ReportObject; import org.intermine.web.logic.session.SessionMethods; /** * * @author radek * */ public class MetabolicGeneSummaryDisplayer extends ReportDisplayer { protected static final Logger LOG = Logger.getLogger(MetabolicGeneSummaryDisplayer.class); /** * Construct with config and the InterMineAPI. * @param config to describe the report displayer * @param im the InterMine API */ public MetabolicGeneSummaryDisplayer(ReportDisplayerConfig config, InterMineAPI im) { super(config, im); } @Override public void display(HttpServletRequest request, ReportObject reportObject) { GeneSummary summary = new GeneSummary(reportObject.getObject(), request); // 1. Pathways count summary.addCollectionCount("Pathways", "description", "pathways", "pathways"); // 2. Diseases count summary.addCollectionCount("Diseases", "description", "diseases", "diseases"); // 3. Mouse Alleles count if (summary.isThisAMouser()) { summary.addCollectionCount("Phenotypes", "straight off mouse", "alleles", "MouseAllelesDisplayer"); } else { summary.addCollectionCount("Phenotypes", "through mouse", allelesPathQuery(summary.getNewPathQuery(), summary.getObjectId()), "MouseAllelesDisplayer"); } // 4. GOTerm count summary.addCollectionCount("Gene Ontology", "description", "goAnnotation", "GeneOntologyDisplayer"); // 5. ArrayExpress Gene Expression Tissues summary.addCustom("Tissues Expression", "ArrayExpress", this.arrayAtlasExpressionTissues( summary.getNewPathQuery(), summary), "gene-expression-atlas-tissues", "metabolicGeneSummaryArrayExpressExpressionTissuesDisplayer.jsp"); // 6. ArrayExpress Gene Expression Diseases summary.addCustom("Diseases Expression", "ArrayExpress", this.arrayAtlasExpressionDiseases( summary.getNewPathQuery(), summary), "gene-expression-atlas-diseases", "metabolicGeneSummaryArrayExpressExpressionDiseasesDisplayer.jsp"); request.setAttribute("summary", summary); } private Object arrayAtlasExpressionTissues(PathQuery query, GeneSummary summary) { query.addViews("Gene.atlasExpression.condition", "Gene.atlasExpression.expression"); query.addOrderBy("Gene.atlasExpression.pValue", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", summary.getObjectId().toString()), "A"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.pValue", "1E-20"), "B"); query.addConstraint(Constraints.neq("Gene.atlasExpression.pValue", "0"), "C"); query.addConstraint(Constraints.eq("Gene.atlasExpression.type", "organism_part"), "D"); query.addConstraint(Constraints.greaterThan("Gene.atlasExpression.tStatistic", "10"), "E"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.tStatistic", "-10"), "F"); query.addConstraint(Constraints.neq("Gene.atlasExpression.condition", "(empty)"), "G"); query.setConstraintLogic("A and B and C and D and (E or F) and G"); ExportResultsIterator results = summary.getExecutor().execute((PathQuery) query); HashMap<String, String> tissues = new HashMap<String, String>(); while (results.hasNext()) { List<ResultElement> item = results.next(); String tissue = item.get(0).getField().toString(); String regulation = item.get(1).getField().toString(); // obviously, we can have the same disease appear 2x (we will), but we don't care... tissues.put(tissue, regulation); } return tissues; } private Object arrayAtlasExpressionDiseases(PathQuery query, GeneSummary summary) { query.addViews("Gene.atlasExpression.condition", "Gene.atlasExpression.expression"); query.addOrderBy("Gene.atlasExpression.pValue", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", summary.getObjectId().toString()), "A"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.pValue", "1E-20"), "B"); query.addConstraint(Constraints.neq("Gene.atlasExpression.pValue", "0"), "C"); query.addConstraint(Constraints.eq("Gene.atlasExpression.type", "disease_state"), "D"); query.addConstraint(Constraints.greaterThan("Gene.atlasExpression.tStatistic", "10"), "E"); query.addConstraint(Constraints.lessThan("Gene.atlasExpression.tStatistic", "-10"), "F"); query.addConstraint(Constraints.neq("Gene.atlasExpression.condition", "(empty)"), "G"); query.setConstraintLogic("A and B and C and D and (E or F) and G"); ExportResultsIterator results = summary.getExecutor().execute((PathQuery) query); HashMap<String, String> diseases = new HashMap<String, String>(); while (results.hasNext()) { List<ResultElement> item = results.next(); String disease = item.get(0).getField().toString(); String regulation = item.get(1).getField().toString(); // obviously, we can have the same disease appear 2x (we will), but we don't care... diseases.put(disease, regulation); } return diseases; } /** * EMTAB-62 link generator from ebi.ac.uk * @param primaryId * @return * @deprecated because the image is too big */ @SuppressWarnings("unused") @java.lang.Deprecated private String emtabExpression(String primaryId) { if (primaryId != null) { return "http: } return null; } /** * Generate PathQuery to Mousey Alleles * @param query * @param objectId * @return */ private PathQuery allelesPathQuery(PathQuery query, Integer objectId) { query.addViews("Gene.homologues.homologue.alleles.primaryIdentifier"); query.addConstraint(Constraints.eq("Gene.homologues.homologue.organism.shortName", "M. musculus"), "A"); query.addConstraint(Constraints.eq("Gene.id", objectId.toString()), "B"); query.setConstraintLogic("A and B"); return query; } /** * Generate PathQuery to GOTerms * @param query * @param objectId * @return */ @SuppressWarnings("unused") private PathQuery goTermPathQuery(PathQuery query, Integer objectId) { query.addViews("Gene.goAnnotation.ontologyTerm.namespace"); query.addOrderBy("Gene.goAnnotation.ontologyTerm.namespace", OrderDirection.ASC); query.addConstraint(Constraints.eq("Gene.id", objectId.toString())); return query; } /** * * Internal wrapper. * @author radek * */ public class GeneSummary { private InterMineObject imObj; private HttpServletRequest request; private PathQueryExecutor executor; private Model model = null; private LinkedHashMap<String, HashMap<String, Object>> storage; /** * * @param imObj InterMineObject * @param request Request */ public GeneSummary(InterMineObject imObj, HttpServletRequest request) { this.imObj = imObj; this.request = request; storage = new LinkedHashMap<String, HashMap<String, Object>>(); } /** * Add a custom object to the displayer. * @param key to show under in the summary * @param description to show under the title * @param data to save on the wrapper object * @param anchor says where we will scroll onlick, an ID attr of the target element * @param jsp to include that knows how to display us */ public void addCustom(String key, String description, Object data, String anchor, String jsp) { storage.put(key, createWrapper("custom", data, anchor, description, jsp)); } /** * Add collection count to the summary. * @param key to show under in the summary * @param description to show under the title * @param param can be a fieldName or a PathQuery * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addCollectionCount(String key, String description, Object param, String anchor) { if (param instanceof PathQuery) { try { storage.put(key, createWrapper("integer", executor.count((PathQuery) param), anchor, description, null)); } catch (ObjectStoreException e) { LOG.error("Problem running PathQuery " + e.toString()); } } else if (param instanceof String) { Collection<?> coll = null; try { if ((coll = (Collection<?>) imObj.getFieldValue((String) param)) != null) { storage.put(key, createWrapper("integer", coll.size(), anchor, description, null)); } } catch (IllegalAccessException e) { LOG.error("The field " + param + " does not exist"); } } else { storage.put(key, createWrapper("unknown", param, anchor, description, null)); } } private HashMap<String, Object> createWrapper(String type, Object data, String anchor, String description, String jsp) { HashMap<String, Object> inner = new HashMap<String, Object>(); inner.put("type", type); inner.put("data", data); inner.put("anchor", anchor); inner.put("description", description); if (jsp != null) { inner.put("jsp", jsp); } return inner; } /** * Add collection distinct count to the summary. Will get the distinct value referenced * and get their count. * @param key to show under in the summary * @param description to show under the title * @param param can be a fieldName or a PathQuery * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addCollectionDistinctCount(String key, String description, Object param, String anchor) { if (param instanceof PathQuery) { ExportResultsIterator results = executor.execute((PathQuery) param); HashMap<String, Integer> temp = new HashMap<String, Integer>(); while (results.hasNext()) { List<ResultElement> item = results.next(); String value = item.get(0).getField().toString(); if (!temp.keySet().contains(value)) { temp.put(value, 0); } temp.put(value, temp.get(value) + 1); } storage.put(key, createWrapper("map", temp, anchor, description, null)); } else { storage.put(key, createWrapper("unknown", param, anchor, description, null)); } } /** * Add a link to an image for the summary. * @param key to show under in the summary * @param description to show under the title * @param link refers to the src attr of the img element * @param anchor says where we will scroll onlick, an ID attr of the target element */ public void addImageLink(String key, String link, String anchor, String description) { storage.put(key, createWrapper("image", link, anchor, description, null)); } /** * Give us a new PathQuery to work on. * @return PathQuery */ public PathQuery getNewPathQuery() { if (model == null) { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); model = im.getModel(); executor = im.getPathQueryExecutor(SessionMethods.getProfile(session)); } return new PathQuery(model); } /** * * @return InterMineObject ID */ public Integer getObjectId() { return imObj.getId(); } /** * * @return true if we are on a mouseified gene */ public Boolean isThisAMouser() { try { return "Mus".equals(((InterMineObject) imObj.getFieldValue("organism")) .getFieldValue("genus")); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } /** * * @return ReportObject primaryIdentifier */ public String getPrimaryId() { try { return (String) imObj.getFieldValue("primaryIdentifier"); } catch (IllegalAccessException e) { LOG.error("The field primaryIdentifier does not exist"); } return null; } /** * * @return PathQuery Executor */ public PathQueryExecutor getExecutor() { return executor; } /** * * @return Map of the fields configged here for the JSP to traverse */ public LinkedHashMap<String, HashMap<String, Object>> getFields() { return storage; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.biojava.bio.structure; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author Jules Jacobsen <jacobsen@ebi.ac.uk> */ public class ResidueNumberTest extends TestCase { public ResidueNumberTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getChainId method, of class ResidueNumber. */ @Test public void testGetSetChainId() { // System.out.println("getChainId"); ResidueNumber instance = new ResidueNumber("A", 42, ' '); String expResult = "A"; String result = instance.getChainId(); assertEquals(expResult, result); } /** * Test of getInsCode method, of class ResidueNumber. */ @Test public void testGetSetInsCode() { // System.out.println("getInsCode"); ResidueNumber instance = new ResidueNumber("A", 42, ' '); Character expResult = ' '; Character result = instance.getInsCode(); assertEquals(expResult, result); } /** * Test of getSeqNum method, of class ResidueNumber. */ @Test public void testGetSetResidueNumber() { // System.out.println("getSeqNum"); ResidueNumber instance = new ResidueNumber("A", 42, ' '); Integer expResult = 42; Integer result = instance.getSeqNum(); assertEquals(expResult, result); } /** * Test of equals method, of class ResidueNumber. */ @Test public void testEquals() { // System.out.println("equals"); ResidueNumber number1 = new ResidueNumber("A", 42, ' '); ResidueNumber number2 = new ResidueNumber("A", 42, ' '); boolean expResult = true; boolean result = number2.equals(number1); assertEquals(expResult, result); Set<ResidueNumber> numberSet= new HashSet<ResidueNumber>(); numberSet.add(number1); numberSet.add(number2); assertEquals(1, numberSet.size()); } /** * Test of hashCode method, of class ResidueNumber. */ @Test public void testHashCode() { // System.out.println("hashCode"); ResidueNumber instance = new ResidueNumber("A", 42, ' '); int expResult = 93290; int result = instance.hashCode(); assertEquals(expResult, result); } /** * Test of toString method, of class ResidueNumber. */ @Test public void testToString() { // System.out.println("toString"); ResidueNumber instance = new ResidueNumber("A", 42, ' '); String expResult = "42"; String result = instance.toString(); assertEquals(expResult, result); } /** * Test of toPDB method, of class ResidueNumber. */ @Test public void testToPDB() { ResidueNumber instance = new ResidueNumber("A", 42, ' '); ResidueNumber instance2 = new ResidueNumber("A", 42, null); String expResult = "A 42 "; String result1 = instance.toPDB(); assertEquals(expResult, result1); String result2 = instance2.toPDB(); assertEquals(expResult, result2); } }
package de.tudresden.inf.lat.born.gui.processor; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import de.tudresden.inf.lat.born.gui.BornIcon; import de.tudresden.inf.lat.born.gui.Message; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorConfiguration; /** * This is the panel to compute inference. * * @author Julian Mendez */ public class ProcessorView extends JPanel { private static final long serialVersionUID = -3489883631448640992L; public static final String WRONG_FILE_NAME_ERROR_MESSAGE = "WRONG FILE NAME! private JButton buttonInputOntologyFile = new JButton(); private JButton buttonBayesianNetwork = new JButton(); private JButton buttonConsoleInput = new JButton(); private JButton buttonConsoleOutput = new JButton(); private JButton buttonComputeInference = new JButton(); private JLabel labelProgress = new JLabel("computing ..."); private JTextField textInputOntologyFile = new JTextField(); private JTextField textBayesianNetworkFile = new JTextField(); private JTextArea textConsoleInput = new JTextArea(); private JTextArea textConsoleOutput = new JTextArea(); private JScrollPane scrollConsoleInput = new JScrollPane(); private JScrollPane scrollConsoleOutput = new JScrollPane(); private final ProcessorConfiguration model; public ProcessorView(ProcessorConfiguration model) { if (model == null) { throw new IllegalArgumentException("Null argument."); } this.model = model; setLayout(null); createPanel(); } public void addButtonInputOntologyListener(ActionListener listener, String actionCommand) { if (listener == null) { throw new IllegalArgumentException("Null argument."); } if (actionCommand == null) { throw new IllegalArgumentException("Null argument."); } this.buttonInputOntologyFile.addActionListener(listener); this.buttonInputOntologyFile.setActionCommand(actionCommand); } public void addButtonBayesianNetworkListener(ActionListener listener, String actionCommand) { if (listener == null) { throw new IllegalArgumentException("Null argument."); } if (actionCommand == null) { throw new IllegalArgumentException("Null argument."); } this.buttonBayesianNetwork.addActionListener(listener); this.buttonBayesianNetwork.setActionCommand(actionCommand); } public void addButtonConsoleInputListener(ActionListener listener, String actionCommand) { if (listener == null) { throw new IllegalArgumentException("Null argument."); } if (actionCommand == null) { throw new IllegalArgumentException("Null argument."); } this.buttonConsoleInput.addActionListener(listener); this.buttonConsoleInput.setActionCommand(actionCommand); } public void addButtonConsoleOutputListener(ActionListener listener, String actionCommand) { if (listener == null) { throw new IllegalArgumentException("Null argument."); } if (actionCommand == null) { throw new IllegalArgumentException("Null argument."); } this.buttonConsoleOutput.addActionListener(listener); this.buttonConsoleOutput.setActionCommand(actionCommand); } public void addButtonComputeInferenceListener(ActionListener listener, String actionCommand) { if (listener == null) { throw new IllegalArgumentException("Null argument."); } if (actionCommand == null) { throw new IllegalArgumentException("Null argument."); } this.buttonComputeInference.addActionListener(listener); this.buttonComputeInference.setActionCommand(actionCommand); } void createPanel() { JLabel lblNewLabel = new JLabel("ontology"); lblNewLabel.setBounds(168, 83, 70, 15); add(lblNewLabel); buttonInputOntologyFile.setIcon(BornIcon.OPEN_FILE); buttonInputOntologyFile.setBounds(168, 43, 54, 28); add(buttonInputOntologyFile); buttonInputOntologyFile.setToolTipText(Message.tooltipOpenInputOntologyFile); textInputOntologyFile.setBounds(282, 43, 228, 28); add(textInputOntologyFile); textInputOntologyFile.setToolTipText(Message.tooltipTextFieldInputOntologyFile); textInputOntologyFile.setAlignmentX(LEFT_ALIGNMENT); JLabel lblNewLabel_1 = new JLabel("Bayesian network"); lblNewLabel_1.setBounds(168, 184, 128, 15); add(lblNewLabel_1); buttonBayesianNetwork.setIcon(BornIcon.OPEN_FILE); buttonBayesianNetwork.setBounds(168, 135, 54, 28); add(buttonBayesianNetwork); buttonBayesianNetwork.setToolTipText(Message.tooltipOpenInputOntologyFile); textBayesianNetworkFile.setBounds(282, 152, 228, 28); add(textBayesianNetworkFile); textBayesianNetworkFile.setToolTipText(Message.tooltipTextFieldBayesianNetworkFile); textBayesianNetworkFile.setAlignmentX(LEFT_ALIGNMENT); JLabel lblInput = new JLabel("input"); lblInput.setBounds(168, 283, 70, 15); add(lblInput); buttonConsoleInput.setIcon(BornIcon.OPEN_FILE); buttonConsoleInput.setBounds(168, 246, 54, 28); add(buttonConsoleInput); buttonConsoleInput.setToolTipText(Message.tooltipOpenInputOntologyFile); textBayesianNetworkFile.setBounds(282, 135, 228, 28); add(textBayesianNetworkFile); textConsoleInput.setToolTipText(Message.tooltipTextFieldListOfParents); textConsoleInput.setAlignmentX(LEFT_ALIGNMENT); scrollConsoleInput.setBounds(282, 246, 228, 65); add(scrollConsoleInput); scrollConsoleInput.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollConsoleInput.setViewportView(textConsoleInput); JLabel lblOutput = new JLabel("output"); lblOutput.setBounds(168, 395, 70, 15); add(lblOutput); textConsoleOutput.setToolTipText(Message.tooltipTextFieldOutputFile); textConsoleOutput.setAlignmentX(LEFT_ALIGNMENT); scrollConsoleOutput.setViewportView(textConsoleOutput); buttonConsoleOutput.setIcon(BornIcon.SAVE_FILE); buttonConsoleOutput.setBounds(168, 355, 54, 28); add(buttonConsoleOutput); buttonConsoleOutput.setToolTipText(Message.tooltipOpenInputOntologyFile); scrollConsoleOutput.setBounds(282, 355, 228, 65); add(scrollConsoleOutput); scrollConsoleOutput.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); buttonComputeInference.setIcon(BornIcon.RUN); buttonComputeInference.setBounds(168, 476, 54, 28); add(buttonComputeInference); buttonComputeInference.setToolTipText(Message.tooltipComputeInference); labelProgress.setBounds(168, 516, 99, 15); labelProgress.setVisible(false); add(labelProgress); } String read(Reader r) throws IOException { StringBuffer sbuf = new StringBuffer(); BufferedReader in = new BufferedReader(r); for (String line = in.readLine(); line != null; line = in.readLine()) { sbuf.append(line); sbuf.append("\n"); } return sbuf.toString(); } void write(Reader input, Writer output) throws IOException { BufferedWriter out = new BufferedWriter(output); BufferedReader in = new BufferedReader(input); for (String line = in.readLine(); line != null; line = in.readLine()) { out.write(line); out.newLine(); } out.flush(); } public ProcessorConfiguration getModel() { return this.model; } public String getInputOntology() { return this.textInputOntologyFile.getText(); } public void setInputOntology(String fileName) { this.textInputOntologyFile.setText(fileName); updateInputOntologyFile(); } public String getBayesianNetwork() { return this.textBayesianNetworkFile.getText(); } public void setBayesianNetwork(String fileName) { this.textBayesianNetworkFile.setText(fileName); updateBayesianNetworkFile(); } public String getConsoleInput() { return this.textConsoleInput.getText(); } public void setConsoleInput(String text) { this.textConsoleInput.setText(text); updateQuery(); } public void readConsoleInput(String consoleInputFile) { if (consoleInputFile != null && !consoleInputFile.trim().isEmpty()) { try { String text = read(new FileReader(consoleInputFile)); this.textConsoleInput.setText(text); updateQuery(); } catch (IOException e) { setInputOntology(WRONG_FILE_NAME_ERROR_MESSAGE); } } } public void writeConsoleOutput(String consoleOutputFile) { if (consoleOutputFile != null && !consoleOutputFile.trim().isEmpty()) { try { String text = this.textConsoleOutput.getText(); write(new StringReader(text), new FileWriter(consoleOutputFile)); } catch (IOException e) { setInputOntology(WRONG_FILE_NAME_ERROR_MESSAGE); } } } public String getConsoleOutput() { return this.textConsoleOutput.getText(); } public void setConsoleOutput(String fileName) { this.textConsoleOutput.setText(fileName); } public void setButtonLoadEnabled(boolean b) { this.buttonInputOntologyFile.setEnabled(b); } public void setButtonComputeInferenceEnabled(boolean b) { this.buttonComputeInference.setEnabled(b); } void updateInputOntologyFile() { String inputOntologyFile = getInputOntology(); if (inputOntologyFile != null && !inputOntologyFile.trim().isEmpty()) { try { getModel().setOntologyInputStream(new FileInputStream(inputOntologyFile)); } catch (IOException e) { setInputOntology(WRONG_FILE_NAME_ERROR_MESSAGE); } } } void updateBayesianNetworkFile() { String bayesianNetworkFile = getBayesianNetwork(); if (bayesianNetworkFile != null && !bayesianNetworkFile.trim().isEmpty()) { try { getModel().setBayesianNetworkInputStream(new FileInputStream(bayesianNetworkFile)); } catch (IOException e) { setBayesianNetwork(WRONG_FILE_NAME_ERROR_MESSAGE); } } } void updateQuery() { String query = this.textConsoleInput.getText(); if (query != null && !query.trim().isEmpty()) { getModel().setQueryInputStream(new ByteArrayInputStream(query.getBytes())); } } public void setResult(String result) { this.textConsoleOutput.setText(result); } public void setComputing(boolean status) { labelProgress.setVisible(status); } public void setButtonsEnabled(boolean status) { buttonInputOntologyFile.setEnabled(status); buttonBayesianNetwork.setEnabled(status); buttonConsoleInput.setEnabled(status); buttonConsoleOutput.setEnabled(status); buttonComputeInference.setEnabled(status); } }
// Observatory Control System, Gemini Telescopes Project. // $Id: ITarget.java 18053 2009-02-20 20:16:23Z swalker $ package edu.gemini.spModel.target.system; import edu.gemini.shared.skyobject.Magnitude; import edu.gemini.shared.util.immutable.*; import edu.gemini.skycalc.Coordinates; import edu.gemini.spModel.target.SpatialProfile; import edu.gemini.spModel.target.SpectralDistribution; import edu.gemini.spModel.target.system.CoordinateTypes.Epoch; import java.io.Serializable; import java.util.HashSet; import java.util.Set; /** * This class describes methods that must be implemented by * all coordinate systems. A coordinate system consists of a * set of parameters that describe the position of a celestial object. * * @author Kim Gillies */ public abstract class ITarget implements Cloneable, Serializable { public enum Tag { // N.B. these strings are meaningful to the TCC, catalog, and are used in PIO XML SIDEREAL("J2000", "Sidereal Target"), NAMED("Solar system object"), JPL_MINOR_BODY("JPL minor body", "JPL minor body (Comet)"), MPC_MINOR_PLANET("MPC minor planet", "MPC minor planet (Asteroid)"); public final String tccName; public final String friendlyName; Tag(String tccName, String friendlyName) { this.tccName = tccName; this.friendlyName = friendlyName; } Tag(String tccName) { this(tccName, tccName); } @Override public String toString() { return friendlyName; } } public static ITarget forTag(Tag tag) { switch (tag) { case JPL_MINOR_BODY: return new ConicTarget(ITarget.Tag.JPL_MINOR_BODY); case MPC_MINOR_PLANET: return new ConicTarget(ITarget.Tag.MPC_MINOR_PLANET); case NAMED: return new NamedTarget(); case SIDEREAL: return new HmsDegTarget(); } throw new Error("unpossible"); } /** Get the name. */ public abstract String getName(); /// TRANSITIONAL ACCESSORS public Option<Double> getRaDegrees(Option<Long> time) { return new Some(getRa().getAs(CoordinateParam.Units.DEGREES)); } public Option<Double> getRaHours(Option<Long> time) { return new Some(getRa().getAs(CoordinateParam.Units.HMS)); } public double getRaHours() { return getRa().getAs(CoordinateParam.Units.HMS); } public Option<String> getRaString(Option<Long> time) { return new Some(getRa().toString()); } /// TRANSITIONAL PACKAGE-PRIVATE abstract void setName(String name); abstract HMS getRa(); void setRaDegrees(double value) { getRa().setAs(value, CoordinateParam.Units.DEGREES); } void setRaHours(double value) { getRa().setAs(value, CoordinateParam.Units.HMS); } // TRANSITIONAL void setRaString(String s) { getRa().setValue(s); } // TRANSITIONAL void setRaDecDegrees(double ra, double dec) { setRaDegrees(ra); setDecDegrees(dec); } /** Get the Dec. */ protected abstract DMS getDec(); public Option<Double> getDecDegrees(Option<Long> time) { return new Some(getDecDegrees()); } // TRANSITIONAL public double getDecDegrees() { return getDec().getAs(CoordinateParam.Units.DEGREES); } // TRANSITIONAL void setDecDegrees(double value) { getDec().setAs(value, CoordinateParam.Units.DEGREES); } // TRANSITIONAL public Option<String> getDecString(Option<Long> time) { return new Some(getDec().toString()); } // TRANSITIONAL void setDecString(String s) { getDec().setValue(s); } /** Get the Epoch */ public abstract Epoch getEpoch(); /** Set the Epoch */ abstract void setEpoch(Epoch e); // RCN: pushed across from SPTarget private ImList<Magnitude> magnitudes = ImCollections.emptyList(); private scala.Option<SpectralDistribution> spectralDistribution = scala.Option.empty(); private scala.Option<SpatialProfile> spatialProfile = scala.Option.empty(); /** * Gets all the {@link Magnitude} information associated with this target, * if any. * * @return (possibly empty) immutable list of {@link Magnitude} values * associated with this target */ public ImList<Magnitude> getMagnitudes() { return magnitudes; } /** * Filters {@link Magnitude} values with the same passband. * * @param magList original magnitude list possibly containing values with * duplicate passbands * * @return immutable list of {@link Magnitude} where each value in the * list is guaranteed to have a distinct passband */ private static ImList<Magnitude> filterDuplicates(final ImList<Magnitude> magList) { return magList.filter(new PredicateOp<Magnitude>() { private final Set<Magnitude.Band> bands = new HashSet<>(); @Override public Boolean apply(final Magnitude magnitude) { final Magnitude.Band band = magnitude.getBand(); if (bands.contains(band)) return false; bands.add(band); return true; } }); } /** * Assigns the list of magnitudes to associate with this target. If there * are multiple magnitudes associated with the same bandpass, only one will * be kept. * * @param magnitudes new collection of magnitude information to store with * the target */ void setMagnitudes(final ImList<Magnitude> magnitudes) { this.magnitudes = filterDuplicates(magnitudes); } /** * Gets the {@link Magnitude} value associated with the given magnitude * passband. * * @param band passband of the {@link Magnitude} value to retrieve * * @return {@link Magnitude} value associated with the given passband, * wrapped in a {@link edu.gemini.shared.util.immutable.Some} object; {@link edu.gemini.shared.util.immutable.None} if none */ public Option<Magnitude> getMagnitude(final Magnitude.Band band) { return magnitudes.find(magnitude -> band.equals(magnitude.getBand())); } /** * Gets the set of magnitude bands that have been recorded in this target. * * @returns a Set of {@link Magnitude.Band magnitude bands} for which * we have information in this target */ public Set<Magnitude.Band> getMagnitudeBands() { final ImList<Magnitude.Band> bandList = magnitudes.map(magnitude -> magnitude.getBand()); return new HashSet<>(bandList.toList()); } /** * Adds the given magnitude to the collection of magnitudes associated with * this target, replacing any other magnitude of the same band if any. * * @param mag magnitude information to add to the collection of magnitudes */ void putMagnitude(final Magnitude mag) { magnitudes = magnitudes.filter(cur -> cur.getBand() != mag.getBand()).cons(mag); } void setSpectralDistribution(scala.Option<SpectralDistribution> sd) { spectralDistribution = sd; } public scala.Option<SpectralDistribution> getSpectralDistribution() { return spectralDistribution; } void setSpatialProfile(scala.Option<SpatialProfile> sp) { spatialProfile = sp; } public scala.Option<SpatialProfile> getSpatialProfile() { return spatialProfile; } // pushed down from CoordinateSystem public ITarget clone() { try { return (ITarget) super.clone(); } catch (CloneNotSupportedException cnse) { throw new Error(cnse); } } public abstract Tag getTag(); /** Gets a Skycalc {@link edu.gemini.skycalc.Coordinates} representation. */ public synchronized Coordinates getSkycalcCoordinates() { return new Coordinates(getRa().getAs(CoordinateParam.Units.DEGREES), getDec().getAs(CoordinateParam.Units.DEGREES)); } /** Gets a Skycalc {@link edu.gemini.skycalc.Coordinates} representation. */ public synchronized Option<Coordinates> getSkycalcCoordinates(Option<Long> when) { return getRaDegrees(when).flatMap(ra -> getDecDegrees(when).map(dec -> new Coordinates(ra, dec) )); } public final String toString() { return String.format("ITarget(%s, %s)", getTag(), getName()); } }
package org.treetank.access; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.treetank.api.IItem; import org.treetank.api.IItemList; import org.treetank.cache.ICache; import org.treetank.cache.NodePageContainer; import org.treetank.cache.RAMCache; import org.treetank.exception.TTIOException; import org.treetank.io.IReader; import org.treetank.node.DeletedNode; import org.treetank.page.AbsPage; import org.treetank.page.IndirectPage; import org.treetank.page.NamePage; import org.treetank.page.NodePage; import org.treetank.page.PageReference; import org.treetank.page.RevisionRootPage; import org.treetank.page.UberPage; import org.treetank.settings.ERevisioning; import org.treetank.utils.IConstants; /** * <h1>ReadTransactionState</h1> * * <p> * State of a reading transaction. The only thing shared amongst transactions is the page cache. Everything * else is exclusive to this transaction. It is required that only a single thread has access to this * transaction. * </p> * * <p> * A path-like cache boosts sequential operations. * </p> */ @Deprecated public class ReadTransactionState { /** Page reader exclusively assigned to this transaction. */ private final IReader mPageReader; /** Uber page this transaction is bound to. */ private final UberPage mUberPage; /** Cached name page of this revision. */ private final RevisionRootPage mRootPage; /** Read-transaction-exclusive item list. */ private final IItemList mItemList; /** Internal reference to cache. */ private final ICache mCache; /** Configuration of the session */ protected final Session mSession; /** * Standard constructor. * * @param paramSessionState * State of state. * @param paramUberPage * Uber page to start reading with. * @param paramRevision * Key of revision to read from uber page. * @param paramItemList * List of non-persistent items. * @param paramReader * for this transaction * @throws TTIOException * if the read of the persistent storage fails */ protected ReadTransactionState(final Session paramSessionState, final UberPage paramUberPage, final long paramRevision, final IItemList paramItemList, final IReader paramReader) throws TTIOException { mCache = new RAMCache(); mSession = paramSessionState; mPageReader = paramReader; mUberPage = paramUberPage; mRootPage = loadRevRoot(paramRevision); initializeNamePage(); mItemList = paramItemList; } /** * Getting the node related to the given node key. * * @param paramNodeKey * searched for * @return the related Node * @throws TTIOException * if the read to the persistent storage fails */ protected IItem getNode(final long paramNodeKey) throws TTIOException { // Immediately return node from item list if node key negative. if (paramNodeKey < 0) { return mItemList.getItem(paramNodeKey); } // Calculate page and node part for given nodeKey. final long nodePageKey = nodePageKey(paramNodeKey); final int nodePageOffset = nodePageOffset(paramNodeKey); NodePageContainer cont = mCache.get(nodePageKey); if (cont == null) { final NodePage[] revs = getSnapshotPages(nodePageKey); final int mileStoneRevision = mSession.mResourceConfig.mRevisionsToRestore; // Build up the complete page. final ERevisioning revision = mSession.mResourceConfig.mRevision; final NodePage completePage = revision.combinePages(revs, mileStoneRevision); cont = new NodePageContainer(completePage); mCache.put(nodePageKey, cont); } // If nodePage is a weak one, the moveto is not cached final IItem returnVal = cont.getComplete().getNode(nodePageOffset); return checkItemIfDeleted(returnVal); } /** * Method to check if an {@link IItem} is a deleted one. * * @param mToCheck * of the IItem * @return the item if it is valid, null otherwise */ protected final IItem checkItemIfDeleted(final IItem mToCheck) { if (mToCheck instanceof DeletedNode) { return null; } else { return mToCheck; } } /** * Getting the name corresponding to the given key. * * @param mNameKey * for the term searched * @return the name */ protected String getName(final int mNameKey) { return ((NamePage)mRootPage.getNamePageReference().getPage()).getName(mNameKey); } /** * Getting the raw name related to the name key. * * @param mNameKey * for the raw name searched * @return a byte array containing the raw name */ protected final byte[] getRawName(final int mNameKey) { return ((NamePage)mRootPage.getNamePageReference().getPage()).getRawName(mNameKey); } /** * Closing this Readtransaction. * * @throws TTIOException * if the closing to the persistent storage fails. */ protected void close() throws TTIOException { mPageReader.close(); mCache.clear(); } /** * Get revision root page belonging to revision key. * * @param revisionKey * Key of revision to find revision root page for. * @return Revision root page of this revision key. * * @throws TTIOException * if something odd happens within the creation process. */ protected final RevisionRootPage loadRevRoot(final long revisionKey) throws TTIOException { final PageReference ref = dereferenceLeafOfTree(mUberPage.getIndirectPageReference(), revisionKey); if (ref.getPage() == null && ref.getKey() == null) { throw new TTIOException( "Revision will not be loaded since neither the key nor the page is referencable."); } RevisionRootPage page = (RevisionRootPage)ref.getPage(); // If there is no page, get it from the storage and cache it. if (page == null) { page = (RevisionRootPage)mPageReader.read(ref); } // Get revision root page which is the leaf of the indirect tree. return page; } /** * Initialize NamePage. * * @throws TTIOException * if something odd happens during initialization */ protected final void initializeNamePage() throws TTIOException { final PageReference ref = mRootPage.getNamePageReference(); if (ref.getPage() == null) { ref.setPage((NamePage)mPageReader.read(ref)); } } /** * Get UberPage. * * @return The uber page. */ protected final UberPage getUberPage() { return mUberPage; } /** * Get item list. * * @return The item list. */ protected final IItemList getItemList() { return mItemList; } /** * Dereference node page reference. * * @param mNodePageKey * Key of node page. * @return Dereferenced page. * * @throws TTIOException * if something odd happens within the creation process. */ protected final NodePage[] getSnapshotPages(final long mNodePageKey) throws TTIOException { // ..and get all leaves of nodepages from the revision-trees. final List<PageReference> refs = new ArrayList<PageReference>(); final Set<Long> keys = new HashSet<Long>(); for (long i = mRootPage.getRevision(); i >= 0; i final PageReference ref = dereferenceLeafOfTree(loadRevRoot(i).getIndirectPageReference(), mNodePageKey); if (ref != null && (ref.getPage() != null || ref.getKey() != null)) { if (ref.getKey() == null || (!keys.contains(ref.getKey().getIdentifier()))) { refs.add(ref); if (ref.getKey() != null) { keys.add(ref.getKey().getIdentifier()); } } if (refs.size() == mSession.mResourceConfig.mRevisionsToRestore) { break; } } else { break; } } // Afterwards read the nodepages if they are not dereferences... final NodePage[] pages = new NodePage[refs.size()]; for (int i = 0; i < pages.length; i++) { final PageReference rev = refs.get(i); pages[i] = (NodePage)rev.getPage(); if (pages[i] == null) { pages[i] = (NodePage)mPageReader.read(rev); } } return pages; } /** * Dereference indirect page reference. * * @param reference * Reference to dereference. * @return Dereferenced page. * * @throws TTIOException * if something odd happens within the creation process. */ protected final IndirectPage dereferenceIndirectPage(final PageReference reference) throws TTIOException { IndirectPage page = (IndirectPage)reference.getPage(); // If there is no page, get it from the storage and cache it. if (page == null) { page = (IndirectPage)mPageReader.read(reference); reference.setPage(page); } return page; } /** * Find reference pointing to leaf page of an indirect tree. * * @param paramStartReference * Start reference pointing to the indirect tree. * @param paramKey * Key to look up in the indirect tree. * @return Reference denoted by key pointing to the leaf page. * * @throws TTIOException * if something odd happens within the creation process. */ protected final PageReference dereferenceLeafOfTree(final PageReference paramStartReference, final long paramKey) throws TTIOException { // Initial state pointing to the indirect page of level 0. PageReference reference = paramStartReference; int offset = 0; long levelKey = paramKey; // Iterate through all levels. for (int level = 0, height = IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT.length; level < height; level++) { offset = (int)(levelKey >> IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]); levelKey -= offset << IConstants.INP_LEVEL_PAGE_COUNT_EXPONENT[level]; final AbsPage page = dereferenceIndirectPage(reference); if (page == null) { reference = null; break; } else { reference = page.getReference(offset); } } // Return reference to leaf of indirect tree. return reference; } /** * Calculate node page key from a given node key. * * @param mNodeKey * Node key to find node page key for. * @return Node page key. */ protected static final long nodePageKey(final long mNodeKey) { final long nodePageKey = mNodeKey >> IConstants.NDP_NODE_COUNT_EXPONENT; return nodePageKey; } /** * Current reference to actual rev-root page. * * @return the current revision root page * * @throws TTIOException * if something odd happens within the creation process. */ protected RevisionRootPage getActualRevisionRootPage() throws TTIOException { return mRootPage; } /** * Calculate node page offset for a given node key. * * @param mNodeKey * Node key to find offset for. * @return Offset into node page. */ protected static final int nodePageOffset(final long mNodeKey) { final long nodePageOffset = (mNodeKey - ((mNodeKey >> IConstants.NDP_NODE_COUNT_EXPONENT) << IConstants.NDP_NODE_COUNT_EXPONENT)); return (int)nodePageOffset; } /** * {@inheritDoc} */ @Override public String toString() { return new StringBuilder("SessionConfiguration: ").append(mSession.mSessionConfig).append( "\nPageReader: ").append(mPageReader).append("\nUberPage: ").append(mUberPage).append( "\nRevRootPage: ").append(mRootPage).toString(); } }
package gov.nih.nci.ncicb.cadsr.common.lov; /** * A Bean class. * <P> * @author Oracle Corporation */ import gov.nih.nci.ncicb.cadsr.common.resource.Context; import gov.nih.nci.ncicb.cadsr.common.util.*; import gov.nih.nci.ncicb.cadsr.common.util.logging.Log; import gov.nih.nci.ncicb.cadsr.common.util.logging.LogFactory; import java.sql.*; import java.util.Collection; import java.util.Iterator; import javax.servlet.http.*; //import healthtoolkit.beans.dbservice.*; //import healthtoolkit.utils.*; public class ClassificationsLOVBean extends Object { private static Log log = LogFactory.getLog(ClassificationsLOVBean.class.getName()); // private String[] searchName; // private String[] displayName; // private String[] jspParm; // private String[] sqlStmtParm; //private DBBroker dBBroker = null; private CommonLOVBean clb; private String targetJsp = "classificationsLOV.jsp"; private String whereClause = ""; private String[] searchStr = null; private boolean isContextSpecific = false; public ClassificationsLOVBean(HttpServletRequest request ,DBUtil dbUtil ,String additionalWhere ){ getClassificationBean(request, dbUtil, additionalWhere); } public ClassificationsLOVBean( HttpServletRequest req, DBUtil dbUtil, String chk, String contextIdSeq) { // build additional query filters String additionalWhere = getAdditionalWhere(req, chk, contextIdSeq); //call the method to get the bean getClassificationBean(req, dbUtil, additionalWhere); } private void getClassificationBean(HttpServletRequest request , DBUtil dbUtil, String additionalWhere) { try { // searchStr = request.getParameter("SEARCH"); searchStr = request.getParameterValues("SEARCH"); String csWhere = ""; String csvWhere = ""; String csiWhere = ""; if (searchStr != null) { for (int i = 0; i < searchStr.length; i++) { if (searchStr[i] == null) searchStr[i] = ""; } if (!searchStr[0].equals("")) { String newSearchStr0 = StringReplace.strReplace( searchStr[0], "*", "%"); // Release 3.0, TT#1178 newSearchStr0 = StringReplace.strReplace(newSearchStr0, "'", "''"); csWhere = " and (upper (cs.long_name) like upper ( '" + newSearchStr0 + "') " + " OR upper (cs.preferred_name) like upper ( '" + newSearchStr0 + "')) "; } // Release 3.2 GF#1247 if (!searchStr[1].equals("")) { Float newSearchFlt1 = new Float(searchStr[1]); csvWhere = " and cs.version = " + newSearchFlt1.toString() + " "; } if (!searchStr[2].equals("")) { String newSearchStr1 = StringReplace.strReplace( searchStr[2], "*", "%"); // Release 3.0, TT#1178 newSearchStr1 = StringReplace.strReplace(newSearchStr1, "'", "''"); csiWhere = " and upper (csi.long_name) like upper ( '" + newSearchStr1 + "') "; } if (request.getParameter("chkContext") == null) { whereClause = csWhere + csvWhere + csiWhere; } else { whereClause = csWhere + csvWhere + csiWhere + additionalWhere; isContextSpecific = true; } } // pass the following parameters to CommonListCntrlBean String[] searchParm = { "cs.long_name", "CS Long Name", "cs.version", "CS Version", // Release 3.2 GF#1247 "csi.long_name csi_name", "Class Scheme Item" }; String[] jspLinkParm = { "csc.cs_csi_idseq", "P_ID" }; String[] displayParm = { "cs.long_name", "CS Long Name", "cs.cs_id||'v'||" + "case when cs.version = trunc(cs.version) " + "then to_char(cs.version,'99.9') " + "else to_char(cs.version,'99.99') " + "end csversion", "CS Public ID Version", // Release 3.2 GF#1247 "cs_conte.name", "CS Context", "cs.cstl_name", "CS Type", "cs.asl_name", "CS Workflow Status", "cs.preferred_definition", "CS Definition", "csi.long_name csi_name", "Class Scheme Item Name", "csi.csi_id||'v'||" + "case when csi.version = trunc(csi.version) " + "then to_char(csi.version,'99.9') " + "else to_char(csi.version,'99.99') " + "end csi_version", "CSI Public ID Version", "csi.csitl_name", "CSI Type", }; String[] sqlStmtParm = new String[2]; sqlStmtParm[0] = " from sbr.classification_schemes_view cs, sbr.contexts_view cs_conte, " + " sbr.cs_items_view csi, sbr.cs_csi_view csc " + " where cs.conte_idseq = cs_conte.conte_idseq " // Release 3.2 GF#1247 " and cs.latest_version_ind = 'Yes' " //" and cs.deleted_ind = 'No' " //when using view no need for this + " and cs.cs_idseq = csc.cs_idseq " + " and csi.csi_idseq = csc.csi_idseq " + " and cs.asl_name not in ('RETIRED PHASED OUT','RETIRED DELETED') " + whereClause; sqlStmtParm[1] = " order by cs.long_name, csi.long_name "; int[] lovPassbackCols = { 0, 4 }; clb = new CommonLOVBean(request, // dBBroker, dbUtil, searchParm, jspLinkParm, displayParm, sqlStmtParm, false, lovPassbackCols); clb.setCompressFlag(false); // set compress flag clb.setLinkCol(0); // set detail page link column, 0-> first; // 1->second clb.setDetailReq_Type("value_domains"); // set req_type for detail // page clb.setShowRowNum(40); // clb.setPerformQueryToFalse(); clb.setJsId(request.getParameter("idVar")); clb.setJsName(request.getParameter("nameVar")); if (isContextSpecific) clb.setExtraURLInfo("&performQuery=false&ckhContext=yes"); else clb.setExtraURLInfo("&performQuery=false"); } catch (SQLException e) { //this.dBBroker = dBBroker; log.error("Exception: ", e); } } private String getAdditionalWhere(HttpServletRequest req, String chk, String contextIdSeq) { String[] contexts = null; if(chk != null && chk.equals("always")) { Collection coll = (Collection)req.getSession().getAttribute("userContexts"); contexts = new String[coll.size()]; int i=0; for(Iterator it = coll.iterator(); it.hasNext(); i++) contexts[i] = ((Context)it.next()).getConteIdseq(); req.setAttribute("chkContext", chk); } else { if ((contextIdSeq != null) && (contextIdSeq.length() > 0)) { contexts = new String[1]; contexts[0] = contextIdSeq; } else contexts = new String[0]; } // build additional query filters String additionalWhere = ""; if(contexts.length > 0) additionalWhere += " and (upper(nvl(cs_conte.conte_idseq,'%')) like upper ( '%" + contexts[0] + "%') "; for(int i=1; i<contexts.length; i++) { additionalWhere += " or upper(nvl(cs_conte.conte_idseq,'%')) like upper ( '%" + contexts[i] + "%') "; } if(contexts.length > 0) additionalWhere += ")"; //return teh string return additionalWhere; } public CommonLOVBean getCommonLOVBean() { return this.clb; } public String getJsp() { return targetJsp; } public boolean getIsContextSpecific(){ return isContextSpecific; } }
package com.cardshifter.core.cardloader; import java.nio.file.Path; 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.Objects; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import static com.cardshifter.core.cardloader.CardLoaderHelper.*; import com.cardshifter.modapi.attributes.ECSAttribute; import com.cardshifter.modapi.attributes.ECSAttributeMap; import com.cardshifter.modapi.base.Entity; import com.cardshifter.modapi.cards.IdComponent; import com.cardshifter.modapi.resources.ECSResource; import com.cardshifter.modapi.resources.ECSResourceMap; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; /** * A card loader to load cards from XML files. * * @author Frank van Heeswijk */ public class XmlCardLoader implements CardLoader<Path> { @Override public Collection<Entity> loadCards(final Path path, final Supplier<Entity> entitySupplier, final ECSResource[] resources, final ECSAttribute[] attributes) throws CardLoadingException { Objects.requireNonNull(path, "path"); Objects.requireNonNull(entitySupplier, "entitySupplier"); List<ECSResource> resourcesList = (resources == null) ? Arrays.asList() : Arrays.asList(resources); List<ECSAttribute> attributesList = (attributes == null) ? Arrays.asList() : Arrays.asList(attributes); try { SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(path.toFile()); XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat().setExpandEmptyElements(true)); String unformattedXmlString = xmlOutputter.outputString(document); JacksonXmlModule xmlModule = new JacksonXmlModule(); xmlModule.setDefaultUseWrapper(false); ObjectMapper xmlMapper = new XmlMapper(xmlModule); CardInfo cardInfo = xmlMapper.readValue(unformattedXmlString, CardInfo.class); List<String> tags = Stream.concat(resourcesList.stream(), attributesList.stream()) .map(ecsElement -> sanitizeTag(ecsElement.toString())) .collect(Collectors.toList()); if (requiredTags().stream().anyMatch(tags::contains)) { throw new UncheckedCardLoadingException("Tags " + requiredTags() + " are required by default you cannot submit them in the resources or attributes."); } List<String> duplicateTags = tags.stream() .collect(Collectors.groupingBy(i -> i)) .entrySet() .stream() .filter(entry -> entry.getValue().size() > 1) .map(Entry::getKey) .collect(Collectors.toList()); if (!duplicateTags.isEmpty()) { throw new UncheckedCardLoadingException("Tags " + duplicateTags + " have been input multiple times, this is not allowed."); } Map<String, ECSResource> ecsResourcesMap = resourcesList.stream() .collect(Collectors.toMap(ecsResource -> sanitizeTag(ecsResource.toString()), i -> i)); Map<String, ECSAttribute> ecsAttributesMap = attributesList.stream() .collect(Collectors.toMap(ecsAttribute -> sanitizeTag(ecsAttribute.toString()), i -> i)); List<Card> cardList = cardInfo.getCards().getCards(); List<String> duplicateIds = cardList.stream() .collect(Collectors.groupingBy(Card::getId)) .entrySet() .stream() .filter(entry -> entry.getValue().size() > 1) .map(Entry::getKey) .collect(Collectors.toList()); if (!duplicateIds.isEmpty()) { throw new UncheckedCardLoadingException("Card ids " + duplicateIds + " are duplicaties, this is not allowed."); } return cardList.stream() .map(card -> { Entity entity = entitySupplier.get(); entity.addComponent(new IdComponent(card.getId())); ECSResourceMap resourceMap = ECSResourceMap.createFor(entity); ECSAttributeMap attributeMap = ECSAttributeMap.createFor(entity); card.getElements().forEach((sanitizedTag, value) -> { if (ecsResourcesMap.containsKey(sanitizedTag)) { resourceMap.set(ecsResourcesMap.get(sanitizedTag), Integer.parseInt(value.toString())); } else if (ecsAttributesMap.containsKey(sanitizedTag)) { attributeMap.set(ecsAttributesMap.get(sanitizedTag), value.toString()); } else { throw new UncheckedCardLoadingException("Element " + sanitizedTag + " has not been found in the supplied resource and attribute mappings where card id = " + card.getId()); } }); return entity; }) .collect(Collectors.toList()); } catch (UncheckedCardLoadingException ex) { throw new CardLoadingException(ex.getMessage(), ex.getCause()); } catch (Exception ex) { throw new CardLoadingException(ex); } } private static class CardInfo { @JacksonXmlProperty(localName = "Cards") private Cards cards; public Cards getCards() { if (cards == null) { cards = new Cards(); //fix for Cards instance being null on empty cards list } return cards; } } private static class Cards { @JacksonXmlProperty(localName = "Card") private Card[] cards; public List<Card> getCards() { if (cards == null) { cards = new Card[0]; } return Arrays.asList(cards); } } private static class Card { private String id; private boolean duplicateId = false; private final Map<String, Object> elements = new HashMap<>(); private boolean duplicateElements = false; private final List<String> duplicateElementTags = new ArrayList<>(); @JsonAnySetter private void addElement(final String tag, final Object value) { String sanitizedTag = sanitizeTag(tag); switch (sanitizedTag) { case "id": if (id != null) { duplicateId = true; return; } id = value.toString(); break; default: if (elements.containsKey(sanitizedTag)) { duplicateElements = true; duplicateElementTags.add(sanitizedTag); return; } elements.put(sanitizedTag, value); break; } } public String getId() { if (duplicateId) { throw new UncheckedCardLoadingException("Element id has duplicate entries"); } if (id == null) { throw new UncheckedCardLoadingException("Required element id has not been set"); } return id; } @JsonAnyGetter public Map<String, Object> getElements() { if (duplicateElements) { throw new UncheckedCardLoadingException("Elements " + duplicateElementTags + " have duplicate entries where card id = " + id); } return new HashMap<>(elements); } } }
package org.jnosql.diana.cassandra.column; import org.jnosql.diana.api.TypeSupplier; import org.jnosql.diana.api.Value; import org.jnosql.diana.api.column.Column; import java.util.List; import java.util.Objects; /** * On Cassandra, there is the option to a UDT be part of a list. This implementation holds this option. */ class IterableUDT implements UDT { private final String name; private final String userType; private final List<List<Column>> columns; IterableUDT(String name, String userType, List<List<Column>> columns) { this.name = name; this.userType = userType; this.columns = columns; } @Override public String getName() { return name; } @Override public Value getValue() { return Value.of(columns); } @Override public <T> T get(Class<T> clazz) throws NullPointerException, UnsupportedOperationException { Objects.requireNonNull(clazz, "clazz is required"); return Value.of(columns).get(clazz); } @Override public <T> T get(TypeSupplier<T> typeSupplier) throws NullPointerException, UnsupportedOperationException { Objects.requireNonNull(typeSupplier, "typeSupplier is required"); return Value.of(columns).get(typeSupplier); } @Override public Object get() { return columns; } @Override public String getUserType() { return userType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof UDT)) { return false; } UDT udt = (UDT) o; return Objects.equals(name, udt.getName()) && Objects.equals(userType, udt.getUserType()) && Objects.equals(columns, udt.get()); } @Override public int hashCode() { return Objects.hash(name, userType, columns); } @Override public String toString() { final StringBuilder sb = new StringBuilder("UDT{"); sb.append("name='").append(name).append('\''); sb.append(", userType='").append(userType).append('\''); sb.append(", columns=").append(columns); sb.append('}'); return sb.toString(); } }
package ch.obermuhlner.math.big; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; import static java.math.BigDecimal.valueOf; import java.math.BigDecimal; import java.math.MathContext; import java.util.*; import ch.obermuhlner.math.big.internal.AsinCalculator; import ch.obermuhlner.math.big.internal.CosCalculator; import ch.obermuhlner.math.big.internal.CoshCalculator; import ch.obermuhlner.math.big.internal.ExpCalculator; import ch.obermuhlner.math.big.internal.SinCalculator; import ch.obermuhlner.math.big.internal.SinhCalculator; /** * Provides advanced functions operating on {@link BigDecimal}s. */ public class BigDecimalMath { private static final BigDecimal TWO = valueOf(2); private static final BigDecimal THREE = valueOf(3); private static final BigDecimal MINUS_ONE = valueOf(-1); private static final BigDecimal ONE_HALF = valueOf(0.5); private static final BigDecimal DOUBLE_MAX_VALUE = BigDecimal.valueOf(Double.MAX_VALUE); private static volatile BigDecimal log2Cache; private static final Object log2CacheLock = new Object(); private static volatile BigDecimal log3Cache; private static final Object log3CacheLock = new Object(); private static volatile BigDecimal log10Cache; private static final Object log10CacheLock = new Object(); private static volatile BigDecimal piCache; private static final Object piCacheLock = new Object(); private static volatile BigDecimal eCache; private static final Object eCacheLock = new Object(); private static final BigDecimal ROUGHLY_TWO_PI = new BigDecimal("3.141592653589793").multiply(TWO); private static final int EXPECTED_INITIAL_PRECISION = 15; private static BigDecimal[] factorialCache = new BigDecimal[100]; static { BigDecimal result = ONE; factorialCache[0] = result; for (int i = 1; i < factorialCache.length; i++) { result = result.multiply(valueOf(i)); factorialCache[i] = result; } } private static final Map<Integer, List<BigDecimal>> spougeFactorialConstantsCache = new HashMap<>(); private static final Object spougeFactorialConstantsCacheLock = new Object(); private BigDecimalMath() { // prevent instances } /** * Creates a {@link BigDecimal} from the specified <code>String</code> representation. * * <p>This method is equivalent to the String constructor {@link BigDecimal#BigDecimal(String)} * but has been optimized for large strings (several thousand digits).</p> * * @param string the String representation * @return the created {@link BigDecimal} * @throws NumberFormatException if <code>string</code> is not a valid representation of a {@link BigDecimal} * @see BigDecimal#BigDecimal(String) * @see #toBigDecimal(String, MathContext) */ public static BigDecimal toBigDecimal(String string) { return toBigDecimal(string, MathContext.UNLIMITED); } /** * Creates a {@link BigDecimal} from the specified <code>String</code> representation. * * <p>This method is equivalent to the String constructor {@link BigDecimal#BigDecimal(String, MathContext)} * but has been optimized for large strings (several thousand digits).</p> * * @param string the string representation * @param mathContext the {@link MathContext} used for the result * @return the created {@link BigDecimal} * @throws NumberFormatException if <code>string</code> is not a valid representation of a {@link BigDecimal} * @throws ArithmeticException if the result is inexact but the rounding mode is {@code UNNECESSARY} * @see BigDecimal#BigDecimal(String, MathContext) * @see #toBigDecimal(String) */ public static BigDecimal toBigDecimal(String string, MathContext mathContext) { int len = string.length(); if (len < 600) { return new BigDecimal(string, mathContext); } int splitLength = len / (len >= 10000 ? 8 : 5); return toBigDecimal(string, mathContext, splitLength); } static BigDecimal toBigDecimal(String string, MathContext mathContext, int splitLength) { int len = string.length(); if (len < splitLength) { return new BigDecimal(string, mathContext); } char[] chars = string.toCharArray(); boolean numberHasSign = false; boolean negative = false; int numberIndex = 0; int dotIndex = -1; int expIndex = -1; boolean expHasSign = false; int scale = 0; for (int i = 0; i < len; i++) { char c = chars[i]; switch (c) { case '+': if (expIndex >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numberHasSign) { throw new NumberFormatException("Multiple signs in number"); } numberHasSign = true; numberIndex = i + 1; } break; case '-': if (expIndex >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numberHasSign) { throw new NumberFormatException("Multiple signs in number"); } numberHasSign = true; negative = true; numberIndex = i + 1; } break; case 'e': case 'E': if (expIndex >= 0) { throw new NumberFormatException("Multiple exponent markers"); } expIndex = i; break; case '.': if (dotIndex >= 0) { throw new NumberFormatException("Multiple decimal points"); } dotIndex = i; break; default: if (dotIndex >= 0 && expIndex == -1) { scale++; } } } int numberEndIndex; int exp = 0; if (expIndex >= 0) { numberEndIndex = expIndex; String expString = new String(chars, expIndex + 1, len - expIndex - 1); exp = Integer.parseInt(expString); scale = adjustScale(scale, exp); } else { numberEndIndex = len; } BigDecimal result; if (dotIndex >= 0) { int leftLength = dotIndex - numberIndex; BigDecimal bigDecimalLeft = toBigDecimalRecursive(chars, numberIndex, leftLength, exp, splitLength); int rightLength = numberEndIndex - dotIndex - 1; BigDecimal bigDecimalRight = toBigDecimalRecursive(chars, dotIndex + 1, rightLength, exp-rightLength, splitLength); result = bigDecimalLeft.add(bigDecimalRight); } else { result = toBigDecimalRecursive(chars, numberIndex, numberEndIndex - numberIndex, exp, splitLength); } if (scale != 0) { result = result.setScale(scale); } if (negative) { result = result.negate(); } if (mathContext.getPrecision() != 0) { result = result.round(mathContext); } return result; } private static int adjustScale(int scale, long exp) { long adjustedScale = scale - exp; if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE) throw new NumberFormatException("Scale out of range: " + adjustedScale + " while adjusting scale " + scale + " to exponent " + exp); return (int) adjustedScale; } private static BigDecimal toBigDecimalRecursive(char[] chars, int offset, int length, int scale, int splitLength) { if (length > splitLength) { int mid = length / 2; BigDecimal bigDecimalLeft = toBigDecimalRecursive(chars, offset, mid, scale + length - mid, splitLength); BigDecimal bigDecimalRight = toBigDecimalRecursive(chars, offset + mid, length - mid, scale, splitLength); return bigDecimalLeft.add(bigDecimalRight); } if (length == 0) { return BigDecimal.ZERO; } return new BigDecimal(chars, offset, length).movePointRight(scale); } /** * Returns whether the specified {@link BigDecimal} value can be represented as <code>int</code>. * * <p>If this returns <code>true</code> you can call {@link BigDecimal#intValueExact()} without fear of an {@link ArithmeticException}.</p> * * @param value the {@link BigDecimal} to check * @return <code>true</code> if the value can be represented as <code>int</code> value */ public static boolean isIntValue(BigDecimal value) { // TODO impl isIntValue() without exceptions try { value.intValueExact(); return true; } catch (ArithmeticException ex) { // ignored } return false; } /** * Returns whether the specified {@link BigDecimal} value can be represented as <code>long</code>. * * <p>If this returns <code>true</code> you can call {@link BigDecimal#longValueExact()} without fear of an {@link ArithmeticException}.</p> * * @param value the {@link BigDecimal} to check * @return <code>true</code> if the value can be represented as <code>long</code> value */ public static boolean isLongValue(BigDecimal value) { // TODO impl isLongValue() without exceptions try { value.longValueExact(); return true; } catch (ArithmeticException ex) { // ignored } return false; } public static boolean isDoubleValue(BigDecimal value) { if (value.compareTo(DOUBLE_MAX_VALUE) > 0) { return false; } if (value.compareTo(DOUBLE_MAX_VALUE.negate()) < 0) { return false; } return true; } /** * Returns the mantissa of the specified {@link BigDecimal} written as <em>mantissa * 10<sup>exponent</sup></em>. * * <p>The mantissa is defined as having exactly 1 digit before the decimal point.</p> * * @param value the {@link BigDecimal} * @return the mantissa * @see #exponent(BigDecimal) */ public static BigDecimal mantissa(BigDecimal value) { int exponent = exponent(value); if (exponent == 0) { return value; } return value.movePointLeft(exponent); } /** * Returns the exponent of the specified {@link BigDecimal} written as <em>mantissa * 10<sup>exponent</sup></em>. * * <p>The mantissa is defined as having exactly 1 digit before the decimal point.</p> * * @param value the {@link BigDecimal} * @return the exponent * @see #mantissa(BigDecimal) */ public static int exponent(BigDecimal value) { return value.precision() - value.scale() - 1; } public static int significantDigits(BigDecimal value) { BigDecimal stripped = value.stripTrailingZeros(); if (stripped.scale() >= 0) { return stripped.precision(); } else { return stripped.precision() - stripped.scale(); } } /** * Returns the integral part of the specified {@link BigDecimal} (left of the decimal point). * * @param value the {@link BigDecimal} * @return the integral part * @see #fractionalPart(BigDecimal) */ public static BigDecimal integralPart(BigDecimal value) { return value.setScale(0, BigDecimal.ROUND_DOWN); } /** * Returns the fractional part of the specified {@link BigDecimal} (right of the decimal point). * * @param value the {@link BigDecimal} * @return the fractional part * @see #integralPart(BigDecimal) */ public static BigDecimal fractionalPart(BigDecimal value) { return value.subtract(integralPart(value)); } /** * Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext}. * * <p>This method calls {@link BigDecimal#round(MathContext)}.</p> * * @param value the {@link BigDecimal} to round * @param mathContext the {@link MathContext} used for the result * @return the rounded {@link BigDecimal} value * @see BigDecimal#round(MathContext) * @see BigDecimalMath#roundWithTrailingZeroes(BigDecimal, MathContext) */ public static BigDecimal round(BigDecimal value, MathContext mathContext) { return value.round(mathContext); } /** * Rounds the specified {@link BigDecimal} to the precision of the specified {@link MathContext} including trailing zeroes. * * <p>This method is similar to {@link BigDecimal#round(MathContext)} but does <strong>not</strong> remove the trailing zeroes.</p> * * <p>Example:</p> <pre> MathContext mc = new MathContext(5); System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.234567"), mc)); // 1.2346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("123.4567"), mc)); // 123.46 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.001234567"), mc)); // 0.0012346 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.23"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("1.230000"), mc)); // 1.2300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00123"), mc)); // 0.0012300 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0"), mc)); // 0.0000 System.out.println(BigDecimalMath.roundWithTrailingZeroes(new BigDecimal("0.00000000"), mc)); // 0.0000 </pre> * * @param value the {@link BigDecimal} to round * @param mathContext the {@link MathContext} used for the result * @return the rounded {@link BigDecimal} value including trailing zeroes * @see BigDecimal#round(MathContext) * @see BigDecimalMath#round(BigDecimal, MathContext) */ public static BigDecimal roundWithTrailingZeroes(BigDecimal value, MathContext mathContext) { if (value.precision() == mathContext.getPrecision()) { return value; } if (value.signum() == 0) { return BigDecimal.ZERO.setScale(mathContext.getPrecision() - 1); } try { BigDecimal stripped = value.stripTrailingZeros(); int exponentStripped = exponent(stripped); // value.precision() - value.scale() - 1; BigDecimal zero; if (exponentStripped < -1) { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() - exponentStripped); } else { zero = BigDecimal.ZERO.setScale(mathContext.getPrecision() + exponentStripped + 1); } return stripped.add(zero, mathContext); } catch (ArithmeticException ex) { return value.round(mathContext); } } /** * Calculates the reciprocal of the specified {@link BigDecimal}. * * @param x the {@link BigDecimal} * @param mathContext the {@link MathContext} used for the result * @return the reciprocal {@link BigDecimal} * @throws ArithmeticException if x = 0 * @throws ArithmeticException if the result is inexact but the * rounding mode is {@code UNNECESSARY} or * {@code mc.precision == 0} and the quotient has a * non-terminating decimal expansion. */ public static BigDecimal reciprocal(BigDecimal x, MathContext mathContext) { return BigDecimal.ONE.divide(x, mathContext); } /** * Calculates the factorial of the specified integer argument. * * <p>factorial = 1 * 2 * 3 * ... n</p> * * @param n the {@link BigDecimal} * @return the factorial {@link BigDecimal} * @throws ArithmeticException if x &lt; 0 */ public static BigDecimal factorial(int n) { if (n < 0) { throw new ArithmeticException("Illegal factorial(n) for n < 0: n = " + n); } if (n < factorialCache.length) { return factorialCache[n]; } BigDecimal result = factorialCache[factorialCache.length - 1]; return result.multiply(factorialRecursion(factorialCache.length, n)); } private static BigDecimal factorialLoop(int n1, final int n2) { final long limit = Long.MAX_VALUE / n2; long accu = 1; BigDecimal result = BigDecimal.ONE; while (n1 <= n2) { if (accu <= limit) { accu *= n1; } else { result = result.multiply(BigDecimal.valueOf(accu)); accu = n1; } n1++; } return result.multiply(BigDecimal.valueOf(accu)); } private static BigDecimal factorialRecursion(final int n1, final int n2) { int threshold = n1 > 200 ? 80 : 150; if (n2 - n1 < threshold) { return factorialLoop(n1, n2); } final int mid = (n1 + n2) >> 1; return factorialRecursion(mid + 1, n2).multiply(factorialRecursion(n1, mid)); } public static BigDecimal factorial(BigDecimal x, MathContext mathContext) { if (isIntValue(x)) { return round(factorial(x.intValueExact()), mathContext); } checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() << 1, mathContext.getRoundingMode()); int a = mathContext.getPrecision() * 13 / 10; List<BigDecimal> constants = getSpougeFactorialConstants(a); BigDecimal bigA = BigDecimal.valueOf(a); boolean negative = false; BigDecimal factor = constants.get(0); for (int k = 1; k < a; k++) { BigDecimal bigK = BigDecimal.valueOf(k); factor = factor.add(constants.get(k).divide(x.add(bigK), mc), mc); negative = !negative; } BigDecimal result = pow(x.add(bigA, mc), x.add(BigDecimal.valueOf(0.5), mc), mc); result = result.multiply(exp(x.negate().subtract(bigA, mc), mc), mc); result = result.multiply(factor, mc); return round(result, mathContext); } static List<BigDecimal> getSpougeFactorialConstants(int a) { synchronized (spougeFactorialConstantsCacheLock) { return spougeFactorialConstantsCache.computeIfAbsent(a, key -> { List<BigDecimal> constants = new ArrayList<>(a); MathContext mc = new MathContext(a * 15 / 10); BigDecimal c0 = sqrt(pi(mc).multiply(TWO, mc), mc); constants.add(c0); boolean negative = false; BigDecimal factor = c0; for (int k = 1; k < a; k++) { BigDecimal bigK = BigDecimal.valueOf(k); long deltaAK = (long)a - k; BigDecimal ck = pow(BigDecimal.valueOf(deltaAK), bigK.subtract(ONE_HALF, mc), mc); ck = ck.multiply(exp(BigDecimal.valueOf(deltaAK), mc), mc); ck = ck.divide(factorial(k - 1), mc); if (negative) { ck = ck.negate(); } constants.add(ck); negative = !negative; } return Collections.unmodifiableList(constants); }); } } public static BigDecimal gamma(BigDecimal x, MathContext mathContext) { return factorial(x.subtract(ONE), mathContext); } public static BigDecimal bernoulli(int n, MathContext mathContext) { if (n < 0) { throw new ArithmeticException("Illegal bernoulli(n) for n < 0: n = " + n); } BigRational b = BigRational.bernoulli(n); return b.toBigDecimal(mathContext); } /** * Calculates {@link BigDecimal} x to the power of {@link BigDecimal} y (x<sup>y</sup>). * * @param x the {@link BigDecimal} value to take to the power * @param y the {@link BigDecimal} value to serve as exponent * @param mathContext the {@link MathContext} used for the result * @return the calculated x to the power of y with the precision specified in the <code>mathContext</code> * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision * @see #pow(BigDecimal, long, MathContext) */ public static BigDecimal pow(BigDecimal x, BigDecimal y, MathContext mathContext) { checkMathContext(mathContext); if (x.signum() == 0) { switch (y.signum()) { case 0 : return round(ONE, mathContext); case 1 : return round(ZERO, mathContext); } } // TODO optimize y=0, y=1, y=10^k, y=-1, y=-10^k try { long longValue = y.longValueExact(); return pow(x, longValue, mathContext); } catch (ArithmeticException ex) { // ignored } if (fractionalPart(y).signum() == 0) { return powInteger(x, y, mathContext); } // x^y = exp(y*log(x)) MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = exp(y.multiply(log(x, mc), mc), mc); return round(result, mathContext); } public static BigDecimal pow(BigDecimal x, long y, MathContext mathContext) { MathContext mc = mathContext.getPrecision() == 0 ? mathContext : new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode()); // TODO optimize y=0, y=1, y=10^k, y=-1, y=-10^k if (y < 0) { BigDecimal value = reciprocal(pow(x, -y, mc), mc); return round(value, mathContext); } BigDecimal result = ONE; while (y > 0) { if ((y & 1) == 1) { // odd exponent -> multiply result with x result = result.multiply(x, mc); y -= 1; } if (y > 0) { // even exponent -> square x x = x.multiply(x, mc); } y >>= 1; } return round(result, mathContext); } /** * Calculates {@link BigDecimal} x to the power of the integer value y (x<sup>y</sup>). * * <p>The value y MUST be an integer value.</p> * * @param x the {@link BigDecimal} value to take to the power * @param integerY the {@link BigDecimal} <strong>integer</strong> value to serve as exponent * @param mathContext the {@link MathContext} used for the result * @return the calculated x to the power of y with the precision specified in the <code>mathContext</code> * @see #pow(BigDecimal, long, MathContext) */ private static BigDecimal powInteger(BigDecimal x, BigDecimal integerY, MathContext mathContext) { if (fractionalPart(integerY).signum() != 0) { throw new IllegalArgumentException("Not integer value: " + integerY); } if (integerY.signum() < 0) { return ONE.divide(powInteger(x, integerY.negate(), mathContext), mathContext); } MathContext mc = new MathContext(Math.max(mathContext.getPrecision(), -integerY.scale()) + 30, mathContext.getRoundingMode()); BigDecimal result = ONE; while (integerY.signum() > 0) { BigDecimal halfY = integerY.divide(TWO, mc); if (fractionalPart(halfY).signum() != 0) { // odd exponent -> multiply result with x result = result.multiply(x, mc); integerY = integerY.subtract(ONE); halfY = integerY.divide(TWO, mc); } if (halfY.signum() > 0) { // even exponent -> square x x = x.multiply(x, mc); } integerY = halfY; } return round(result, mathContext); } public static BigDecimal sqrt(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); switch (x.signum()) { case 0: return ZERO; case -1: throw new ArithmeticException("Illegal sqrt(x) for x < 0: x = " + x); } int maxPrecision = mathContext.getPrecision() + 6; BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1); BigDecimal result; int adaptivePrecision; if (isDoubleValue(x)) { result = BigDecimal.valueOf(Math.sqrt(x.doubleValue())); adaptivePrecision = EXPECTED_INITIAL_PRECISION; } else { result = x.multiply(ONE_HALF, mathContext); adaptivePrecision = 1; } BigDecimal last; if (adaptivePrecision < maxPrecision) { if (result.multiply(result).compareTo(x) == 0) { return round(result, mathContext); // early exit if x is a square number } do { last = result; adaptivePrecision <<= 1; if (adaptivePrecision > maxPrecision) { adaptivePrecision = maxPrecision; } MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode()); result = x.divide(result, mc).add(last, mc).multiply(ONE_HALF, mc); } while (adaptivePrecision < maxPrecision || result.subtract(last).abs().compareTo(acceptableError) > 0); } return round(result, mathContext); } public static BigDecimal root(BigDecimal x, BigDecimal n, MathContext mathContext) { checkMathContext(mathContext); switch (x.signum()) { case 0: return ZERO; case -1: throw new ArithmeticException("Illegal root(x) for x < 0: x = " + x); } if (n.compareTo(BigDecimal.ONE) <= 0) { MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); return pow(x, BigDecimal.ONE.divide(n, mc), mathContext); } int maxPrecision = mathContext.getPrecision() + 4; BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1); BigDecimal nMinus1 = n.subtract(ONE); BigDecimal result = x.divide(TWO, MathContext.DECIMAL32); int adaptivePrecision = 2; // first approximation has really bad precision BigDecimal step; do { adaptivePrecision *= 3; if (adaptivePrecision > maxPrecision) { adaptivePrecision = maxPrecision; } MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode()); step = x.divide(pow(result, nMinus1, mc), mc).subtract(result, mc).divide(n, mc); result = result.add(step, mc); } while (adaptivePrecision < maxPrecision || step.abs().compareTo(acceptableError) > 0); return round(result, mathContext); } public static BigDecimal log(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.signum() <= 0) { throw new ArithmeticException("Illegal log(x) for x <= 0: x = " + x); } if (x.compareTo(ONE) == 0) { return ZERO; } BigDecimal result; switch (x.compareTo(TEN)) { case 0: result = logTen(mathContext); break; case 1: result = logUsingExponent(x, mathContext); break; default : result = logUsingTwoThree(x, mathContext); } return round(result, mathContext); } /** * Calculates the logarithm of {@link BigDecimal} x to the base 2. * * @param x the {@link BigDecimal} to calculate the logarithm base 2 for * @param mathContext the {@link MathContext} used for the result * @return the calculated natural logarithm {@link BigDecimal} to the base 2 with the precision specified in the <code>mathContext</code> * @throws ArithmeticException if x &lt;= 0 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision */ public static BigDecimal log2(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTwo(mc), mc); return round(result, mathContext); } /** * Calculates the logarithm of {@link BigDecimal} x to the base 10. * * @param x the {@link BigDecimal} to calculate the logarithm base 10 for * @param mathContext the {@link MathContext} used for the result * @return the calculated natural logarithm {@link BigDecimal} to the base 10 with the precision specified in the <code>mathContext</code> * @throws ArithmeticException if x &lt;= 0 * @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision */ public static BigDecimal log10(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 2, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTen(mc), mc); return round(result, mathContext); } private static BigDecimal logUsingNewton(BigDecimal x, MathContext mathContext) { // y = y + 2 * (x-exp(y)) / (x+exp(y)) int maxPrecision = mathContext.getPrecision() + 20; BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1); //System.out.println("logUsingNewton(" + x + " " + mathContext + ") precision " + maxPrecision); BigDecimal result; int adaptivePrecision; double doubleX = x.doubleValue(); if (doubleX > 0.0 && isDoubleValue(x)) { result = BigDecimal.valueOf(Math.log(doubleX)); adaptivePrecision = EXPECTED_INITIAL_PRECISION; } else { result = x.divide(TWO, mathContext); adaptivePrecision = 1; } BigDecimal step; do { adaptivePrecision *= 3; if (adaptivePrecision > maxPrecision) { adaptivePrecision = maxPrecision; } MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode()); BigDecimal expY = BigDecimalMath.exp(result, mc); step = TWO.multiply(x.subtract(expY, mc), mc).divide(x.add(expY, mc), mc); //System.out.println(" step " + step + " adaptivePrecision=" + adaptivePrecision); result = result.add(step); } while (adaptivePrecision < maxPrecision || step.abs().compareTo(acceptableError) > 0); return result; } private static BigDecimal logUsingExponent(BigDecimal x, MathContext mathContext) { MathContext mcDouble = new MathContext(mathContext.getPrecision() << 1, mathContext.getRoundingMode()); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); //System.out.println("logUsingExponent(" + x + " " + mathContext + ") precision " + mc); int exponent = exponent(x); BigDecimal mantissa = mantissa(x); BigDecimal result = logUsingTwoThree(mantissa, mc); if (exponent != 0) { result = result.add(valueOf(exponent).multiply(logTen(mcDouble), mc), mc); } return result; } private static BigDecimal logUsingTwoThree(BigDecimal x, MathContext mathContext) { MathContext mcDouble = new MathContext(mathContext.getPrecision() << 1, mathContext.getRoundingMode()); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); //System.out.println("logUsingTwoThree(" + x + " " + mathContext + ") precision " + mc); int factorOfTwo = 0; int powerOfTwo = 1; int factorOfThree = 0; int powerOfThree = 1; double value = x.doubleValue(); if (value < 0.01) { // do nothing } else if (value < 0.1) { // never happens when called by logUsingExponent() while (value < 0.6) { value *= 2; factorOfTwo powerOfTwo <<= 1; } } else if (value < 0.115) { // (0.1 - 0.11111 - 0.115) -> (0.9 - 1.0 - 1.035) factorOfThree = -2; powerOfThree = 9; } else if (value < 0.14) { // (0.115 - 0.125 - 0.14) -> (0.92 - 1.0 - 1.12) factorOfTwo = -3; powerOfTwo = 8; } else if (value < 0.2) { // (0.14 - 0.16667 - 0.2) - (0.84 - 1.0 - 1.2) factorOfTwo = -1; powerOfTwo = 2; factorOfThree = -1; powerOfThree = 3; } else if (value < 0.3) { // (0.2 - 0.25 - 0.3) -> (0.8 - 1.0 - 1.2) factorOfTwo = -2; powerOfTwo = 4; } else if (value < 0.42) { // (0.3 - 0.33333 - 0.42) -> (0.9 - 1.0 - 1.26) factorOfThree = -1; powerOfThree = 3; } else if (value < 0.7) { // (0.42 - 0.5 - 0.7) -> (0.84 - 1.0 - 1.4) factorOfTwo = -1; powerOfTwo = 2; } else if (value < 1.4) { // (0.7 - 1.0 - 1.4) -> (0.7 - 1.0 - 1.4) // do nothing } else if (value < 2.5) { // (1.4 - 2.0 - 2.5) -> (0.7 - 1.0 - 1.25) factorOfTwo = 1; powerOfTwo = 2; } else if (value < 3.5) { // (2.5 - 3.0 - 3.5) -> (0.833333 - 1.0 - 1.166667) factorOfThree = 1; powerOfThree = 3; } else if (value < 5.0) { // (3.5 - 4.0 - 5.0) -> (0.875 - 1.0 - 1.25) factorOfTwo = 2; powerOfTwo = 4; } else if (value < 7.0) { // (5.0 - 6.0 - 7.0) -> (0.833333 - 1.0 - 1.166667) factorOfThree = 1; powerOfThree = 3; factorOfTwo = 1; powerOfTwo = 2; } else if (value < 8.5) { // (7.0 - 8.0 - 8.5) -> (0.875 - 1.0 - 1.0625) factorOfTwo = 3; powerOfTwo = 8; } else if (value < 10.0) { // (8.5 - 9.0 - 10.0) -> (0.94444 - 1.0 - 1.11111) factorOfThree = 2; powerOfThree = 9; } else { while (value > 1.4) { // never happens when called by logUsingExponent() value /= 2; factorOfTwo++; powerOfTwo <<= 1; } } BigDecimal correctedX = x; BigDecimal result = ZERO; if (factorOfTwo > 0) { correctedX = correctedX.divide(valueOf(powerOfTwo), mc); result = result.add(logTwo(mcDouble).multiply(valueOf(factorOfTwo), mc), mc); } else if (factorOfTwo < 0) { correctedX = correctedX.multiply(valueOf(powerOfTwo), mc); result = result.subtract(logTwo(mcDouble).multiply(valueOf(-factorOfTwo), mc), mc); } if (factorOfThree > 0) { correctedX = correctedX.divide(valueOf(powerOfThree), mc); result = result.add(logThree(mcDouble).multiply(valueOf(factorOfThree), mc), mc); } else if (factorOfThree < 0) { correctedX = correctedX.multiply(valueOf(powerOfThree), mc); result = result.subtract(logThree(mcDouble).multiply(valueOf(-factorOfThree), mc), mc); } if (x == correctedX && result == ZERO) { return logUsingNewton(x, mathContext); } result = result.add(logUsingNewton(correctedX, mc), mc); return result; } public static BigDecimal pi(MathContext mathContext) { checkMathContext(mathContext); BigDecimal result = null; synchronized (piCacheLock) { if (piCache != null && mathContext.getPrecision() <= piCache.precision()) { result = piCache; } else { piCache = piChudnovski(mathContext); return piCache; } } return round(result, mathContext); } private static BigDecimal piChudnovski(MathContext mathContext) { MathContext mc = new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode()); final BigDecimal value24 = BigDecimal.valueOf(24); final BigDecimal value640320 = BigDecimal.valueOf(640320); final BigDecimal value13591409 = BigDecimal.valueOf(13591409); final BigDecimal value545140134 = BigDecimal.valueOf(545140134); final BigDecimal valueDivisor = value640320.pow(3).divide(value24, mc); BigDecimal sumA = BigDecimal.ONE; BigDecimal sumB = BigDecimal.ZERO; BigDecimal a = BigDecimal.ONE; long dividendTerm1 = 5; // -(6*k - 5) long dividendTerm2 = -1; // 2*k - 1 long dividendTerm3 = -1; // 6*k - 1 BigDecimal kPower3 = BigDecimal.ZERO; long iterationCount = (mc.getPrecision()+13) / 14; for (long k = 1; k <= iterationCount; k++) { BigDecimal valueK = BigDecimal.valueOf(k); dividendTerm1 += -6; dividendTerm2 += 2; dividendTerm3 += 6; BigDecimal dividend = BigDecimal.valueOf(dividendTerm1).multiply(BigDecimal.valueOf(dividendTerm2)).multiply(BigDecimal.valueOf(dividendTerm3)); kPower3 = valueK.pow(3); BigDecimal divisor = kPower3.multiply(valueDivisor, mc); a = a.multiply(dividend).divide(divisor, mc); BigDecimal b = valueK.multiply(a, mc); sumA = sumA.add(a); sumB = sumB.add(b); } final BigDecimal value426880 = BigDecimal.valueOf(426880); final BigDecimal value10005 = BigDecimal.valueOf(10005); final BigDecimal factor = value426880.multiply(sqrt(value10005, mc)); BigDecimal pi = factor.divide(value13591409.multiply(sumA, mc).add(value545140134.multiply(sumB, mc)), mc); return round(pi, mathContext); } public static BigDecimal e(MathContext mathContext) { checkMathContext(mathContext); BigDecimal result = null; synchronized (eCacheLock) { if (eCache != null && mathContext.getPrecision() <= eCache.precision()) { result = eCache; } else { eCache = exp(ONE, mathContext); return eCache; } } return round(result, mathContext); } private static BigDecimal logTen(MathContext mathContext) { BigDecimal result = null; synchronized (log10CacheLock) { if (log10Cache != null && mathContext.getPrecision() <= log10Cache.precision()) { result = log10Cache; } else { log10Cache = logUsingNewton(BigDecimal.TEN, mathContext); return log10Cache; } } return round(result, mathContext); } private static BigDecimal logTwo(MathContext mathContext) { BigDecimal result = null; synchronized (log2CacheLock) { if (log2Cache != null && mathContext.getPrecision() <= log2Cache.precision()) { result = log2Cache; } else { log2Cache = logUsingNewton(TWO, mathContext); return log2Cache; } } return round(result, mathContext); } private static BigDecimal logThree(MathContext mathContext) { BigDecimal result = null; synchronized (log3CacheLock) { if (log3Cache != null && mathContext.getPrecision() <= log3Cache.precision()) { result = log3Cache; } else { log3Cache = logUsingNewton(THREE, mathContext); return log3Cache; } } return round(result, mathContext); } public static BigDecimal exp(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.signum() == 0) { return ONE; } return expIntegralFractional(x, mathContext); } private static BigDecimal expIntegralFractional(BigDecimal x, MathContext mathContext) { BigDecimal integralPart = integralPart(x); if (integralPart.signum() == 0) { return expTaylor(x, mathContext); } BigDecimal fractionalPart = x.subtract(integralPart); MathContext mc = new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode()); BigDecimal z = ONE.add(fractionalPart.divide(integralPart, mc)); BigDecimal t = expTaylor(z, mc); BigDecimal result = pow(t, integralPart.intValueExact(), mc); return round(result, mathContext); } private static BigDecimal expTaylor(BigDecimal x, MathContext mathContext) { MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); x = x.divide(valueOf(256), mc); BigDecimal result = ExpCalculator.INSTANCE.calculate(x, mc); result = BigDecimalMath.pow(result, 256, mc); return round(result, mathContext); } public static BigDecimal sin(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); if (x.abs().compareTo(ROUGHLY_TWO_PI) > 0) { MathContext mc2 = new MathContext(mc.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal twoPi = TWO.multiply(pi(mc2), mc2); x = x.remainder(twoPi, mc2); } BigDecimal result = SinCalculator.INSTANCE.calculate(x, mc); return round(result, mathContext); } public static BigDecimal asin(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.compareTo(ONE) > 0) { throw new ArithmeticException("Illegal asin(x) for x > 1: x = " + x); } if (x.compareTo(MINUS_ONE) < 0) { throw new ArithmeticException("Illegal asin(x) for x < -1: x = " + x); } if (x.signum() == -1) { return asin(x.negate(), mathContext).negate(); } MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); if (x.compareTo(BigDecimal.valueOf(0.707107)) >= 0) { BigDecimal xTransformed = sqrt(ONE.subtract(x.multiply(x, mc), mc), mc); return acos(xTransformed, mathContext); } BigDecimal result = AsinCalculator.INSTANCE.calculate(x, mc); return round(result, mathContext); } public static BigDecimal cos(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); if (x.abs().compareTo(ROUGHLY_TWO_PI) > 0) { MathContext mc2 = new MathContext(mc.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal twoPi = TWO.multiply(pi(mc2), mc2); x = x.remainder(twoPi, mc2); } BigDecimal result = CosCalculator.INSTANCE.calculate(x, mc); return round(result, mathContext); } public static BigDecimal acos(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.compareTo(ONE) > 0) { throw new ArithmeticException("Illegal acos(x) for x > 1: x = " + x); } if (x.compareTo(MINUS_ONE) < 0) { throw new ArithmeticException("Illegal acos(x) for x < -1: x = " + x); } MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = pi(mc).divide(TWO, mc).subtract(asin(x, mc), mc); return round(result, mathContext); } public static BigDecimal tan(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.signum() == 0) { return ZERO; } MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = sin(x, mc).divide(cos(x, mc), mc); return round(result, mathContext); } public static BigDecimal atan(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); x = x.divide(sqrt(ONE.add(x.multiply(x, mc), mc), mc), mc); BigDecimal result = asin(x, mc); return round(result, mathContext); } public static BigDecimal atan2(BigDecimal y, BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 3, mathContext.getRoundingMode()); if (x.signum() > 0) { // x > 0 return atan(y.divide(x, mc), mathContext); } else if (x.signum() < 0) { if (y.signum() > 0) { // x < 0 && y > 0 return atan(y.divide(x, mc), mc).add(pi(mc), mathContext); } else if (y.signum() < 0) { // x < 0 && y < 0 return atan(y.divide(x, mc), mc).subtract(pi(mc), mathContext); } else { // x < 0 && y = 0 return pi(mathContext); } } else { if (y.signum() > 0) { // x == 0 && y > 0 return pi(mc).divide(TWO, mathContext); } else if (y.signum() < 0) { // x == 0 && y < 0 return pi(mc).divide(TWO, mathContext).negate(); } else { throw new ArithmeticException("Illegal atan2(y, x) for x = 0; y = 0"); } } } public static BigDecimal cot(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); if (x.signum() == 0) { throw new ArithmeticException("Illegal cot(x) for x = 0"); } MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = cos(x, mc).divide(sin(x, mc), mc); return round(result, mathContext); } public static BigDecimal acot(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = pi(mc).divide(TWO, mc).subtract(atan(x, mc), mc); return round(result, mathContext); } public static BigDecimal sinh(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = SinhCalculator.INSTANCE.calculate(x, mc); return round(result, mathContext); } public static BigDecimal cosh(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = CoshCalculator.INSTANCE.calculate(x, mc); return round(result, mathContext); } public static BigDecimal tanh(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = sinh(x, mc).divide(cosh(x, mc), mc); return round(result, mathContext); } public static BigDecimal coth(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = cosh(x, mc).divide(sinh(x, mc), mc); return round(result, mathContext); } public static BigDecimal asinh(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 10, mathContext.getRoundingMode()); BigDecimal result = log(x.add(sqrt(x.multiply(x, mc).add(ONE, mc), mc), mc), mc); return round(result, mathContext); } public static BigDecimal acosh(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = log(x.add(sqrt(x.multiply(x, mc).subtract(ONE, mc), mc), mc), mc); return round(result, mathContext); } public static BigDecimal atanh(BigDecimal x, MathContext mathContext) { if (x.compareTo(BigDecimal.ONE) >= 0) { throw new ArithmeticException("Illegal atanh(x) for x >= 1: x = " + x); } if (x.compareTo(MINUS_ONE) <= 0) { throw new ArithmeticException("Illegal atanh(x) for x <= -1: x = " + x); } checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = log(ONE.add(x, mc).divide(ONE.subtract(x, mc), mc), mc).multiply(ONE_HALF, mc); return round(result, mathContext); } public static BigDecimal acoth(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 6, mathContext.getRoundingMode()); BigDecimal result = log(x.add(ONE, mc).divide(x.subtract(ONE, mc), mc), mc).divide(TWO, mc); return round(result, mathContext); } private static void checkMathContext (MathContext mathContext) { if (mathContext.getPrecision() == 0) { throw new UnsupportedOperationException("Unlimited MathContext not supported"); } } }
package org.chromium.chrome.browser.infobar; import android.animation.ObjectAnimator; import android.app.Activity; import android.graphics.Canvas; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.google.common.annotations.VisibleForTesting; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.base.CalledByNative; import org.chromium.content_public.browser.WebContents; import org.chromium.ui.UiUtils; import org.chromium.ui.base.DeviceFormFactor; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; /** * A container for all the infobars of a specific tab. * Note that infobars creation can be initiated from Java of from native code. * When initiated from native code, special code is needed to keep the Java and native infobar in * sync, see NativeInfoBar. */ public class InfoBarContainer extends LinearLayout { private static final String TAG = "InfoBarContainer"; private static final long REATTACH_FADE_IN_MS = 250; /** * A listener for the InfoBar animation. */ public interface InfoBarAnimationListener { /** * Notifies the subscriber when an animation is completed. */ void notifyAnimationFinished(int animationType); } private static class InfoBarTransitionInfo { // InfoBar being animated. public InfoBar target; // View to replace the current View shown by the ContentWrapperView. public View toShow; // Which type of animation needs to be performed. public int animationType; public InfoBarTransitionInfo(InfoBar bar, View view, int type) { assert type >= AnimationHelper.ANIMATION_TYPE_SHOW; assert type < AnimationHelper.ANIMATION_TYPE_BOUNDARY; target = bar; toShow = view; animationType = type; } } private InfoBarAnimationListener mAnimationListener; // Native InfoBarContainer pointer which will be set by nativeInit() private long mNativeInfoBarContainer; private final Activity mActivity; private final AutoLoginDelegate mAutoLoginDelegate; // Whether the infobar are shown on top (below the location bar) or at the bottom of the screen. private final boolean mInfoBarsOnTop; // The list of all infobars in this container, regardless of whether they've been shown yet. private final ArrayList<InfoBar> mInfoBars = new ArrayList<InfoBar>(); // We only animate changing infobars one at a time. private final ArrayDeque<InfoBarTransitionInfo> mInfoBarTransitions; // Animation currently moving InfoBars around. private AnimationHelper mAnimation; private final FrameLayout mAnimationSizer; // True when this container has been emptied and its native counterpart has been destroyed. private boolean mDestroyed = false; // The id of the tab associated with us. Set to Tab.INVALID_TAB_ID if no tab is associated. private int mTabId; // Parent view that contains us. private ViewGroup mParentView; public InfoBarContainer(Activity activity, AutoLoginProcessor autoLoginProcessor, int tabId, ViewGroup parentView, WebContents webContents) { super(activity); setOrientation(LinearLayout.VERTICAL); mAnimationListener = null; mInfoBarTransitions = new ArrayDeque<InfoBarTransitionInfo>(); mAutoLoginDelegate = new AutoLoginDelegate(autoLoginProcessor, activity); mActivity = activity; mTabId = tabId; mParentView = parentView; mAnimationSizer = new FrameLayout(activity); mAnimationSizer.setVisibility(INVISIBLE); // The tablet has the infobars below the location bar. On the phone they are at the bottom. mInfoBarsOnTop = DeviceFormFactor.isTablet(activity); setGravity(determineGravity()); // Chromium's InfoBarContainer may add an InfoBar immediately during this initialization // call, so make sure everything in the InfoBarContainer is completely ready beforehand. mNativeInfoBarContainer = nativeInit(webContents, mAutoLoginDelegate); } public void setAnimationListener(InfoBarAnimationListener listener) { mAnimationListener = listener; } @VisibleForTesting public InfoBarAnimationListener getAnimationListener() { return mAnimationListener; } public boolean areInfoBarsOnTop() { return mInfoBarsOnTop; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // Trap any attempts to fiddle with the Views while we're animating. return mAnimation != null; } @Override public boolean onTouchEvent(MotionEvent event) { // Consume all motion events so they do not reach the ContentView. return true; } private void addToParentView() { if (mParentView != null && mParentView.indexOfChild(this) == -1) { mParentView.addView(this, createLayoutParams()); } } private int determineGravity() { return mInfoBarsOnTop ? Gravity.TOP : Gravity.BOTTOM; } private FrameLayout.LayoutParams createLayoutParams() { return new FrameLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, determineGravity()); } public void removeFromParentView() { if (getParent() != null) { ((ViewGroup) getParent()).removeView(this); } } /** * Called when the parent {@link android.view.ViewGroup} has changed for * this container. */ public void onParentViewChanged(int tabId, ViewGroup parentView) { mTabId = tabId; mParentView = parentView; removeFromParentView(); addToParentView(); } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { if (mAnimation == null || child != mAnimation.getTarget()) { return super.drawChild(canvas, child, drawingTime); } // When infobars are on top, the new infobar Z-order is greater than the previous infobar, // which means it shows on top during the animation. We cannot change the Z-order in the // linear layout, it is driven by the insertion index. // So we simply clip the children to their bounds to make sure the new infobar does not // paint over. boolean retVal; canvas.save(); canvas.clipRect(mAnimation.getTarget().getClippingRect()); retVal = super.drawChild(canvas, child, drawingTime); canvas.restore(); return retVal; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); ObjectAnimator.ofFloat(this, "alpha", 0.f, 1.f).setDuration(REATTACH_FADE_IN_MS).start(); setVisibility(VISIBLE); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); setVisibility(INVISIBLE); } /** * Adds an InfoBar to the view hierarchy. * @param infoBar InfoBar to add to the View hierarchy. */ @CalledByNative public void addInfoBar(InfoBar infoBar) { assert !mDestroyed; if (infoBar == null) { return; } if (mInfoBars.contains(infoBar)) { assert false : "Trying to add an info bar that has already been added."; return; } // We add the infobar immediately to mInfoBars but we wait for the animation to end to // notify it's been added, as tests rely on this notification but expects the infobar view // to be available when they get the notification. mInfoBars.add(infoBar); infoBar.setContext(mActivity); infoBar.setInfoBarContainer(this); enqueueInfoBarAnimation(infoBar, null, AnimationHelper.ANIMATION_TYPE_SHOW); } /** * Returns the latest InfoBarTransitionInfo that deals with the given InfoBar. * @param toFind InfoBar that we're looking for. */ public InfoBarTransitionInfo findLastTransitionForInfoBar(InfoBar toFind) { Iterator<InfoBarTransitionInfo> iterator = mInfoBarTransitions.descendingIterator(); while (iterator.hasNext()) { InfoBarTransitionInfo info = iterator.next(); if (info.target == toFind) return info; } return null; } /** * Animates swapping out the current View in the {@code infoBar} with {@code toShow} without * destroying or dismissing the entire InfoBar. * @param infoBar InfoBar that is having its content replaced. * @param toShow View representing the InfoBar's new contents. */ public void swapInfoBarViews(InfoBar infoBar, View toShow) { assert !mDestroyed; if (!mInfoBars.contains(infoBar)) { assert false : "Trying to swap an InfoBar that is not in this container."; return; } InfoBarTransitionInfo transition = findLastTransitionForInfoBar(infoBar); if (transition != null && transition.toShow == toShow) { assert false : "Tried to enqueue the same swap twice in a row."; return; } enqueueInfoBarAnimation(infoBar, toShow, AnimationHelper.ANIMATION_TYPE_SWAP); } /** * Removes an InfoBar from the view hierarchy. * @param infoBar InfoBar to remove from the View hierarchy. */ public void removeInfoBar(InfoBar infoBar) { assert !mDestroyed; if (!mInfoBars.remove(infoBar)) { assert false : "Trying to remove an InfoBar that is not in this container."; return; } // If an InfoBar is told to hide itself before it has a chance to be shown, don't bother // with animating any of it. boolean collapseAnimations = false; ArrayDeque<InfoBarTransitionInfo> transitionCopy = new ArrayDeque<InfoBarTransitionInfo>(mInfoBarTransitions); for (InfoBarTransitionInfo info : transitionCopy) { if (info.target == infoBar) { if (info.animationType == AnimationHelper.ANIMATION_TYPE_SHOW) { // We can assert that two attempts to show the same InfoBar won't be in the // deque simultaneously because of the check in addInfoBar(). assert !collapseAnimations; collapseAnimations = true; } if (collapseAnimations) { mInfoBarTransitions.remove(info); } } } if (!collapseAnimations) { enqueueInfoBarAnimation(infoBar, null, AnimationHelper.ANIMATION_TYPE_HIDE); } } /** * Enqueue a new animation to run and kicks off the animation sequence. */ private void enqueueInfoBarAnimation(InfoBar infoBar, View toShow, int animationType) { InfoBarTransitionInfo info = new InfoBarTransitionInfo(infoBar, toShow, animationType); mInfoBarTransitions.add(info); processPendingInfoBars(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // Hide the infobars when the keyboard is showing. boolean isShowing = (getVisibility() == View.VISIBLE); if (UiUtils.isKeyboardShowing(mActivity, this)) { if (isShowing) { setVisibility(View.INVISIBLE); } } else { if (!isShowing) { setVisibility(View.VISIBLE); } } super.onLayout(changed, l, t, r, b); } /** * @return True when this container has been emptied and its native counterpart has been * destroyed. */ public boolean hasBeenDestroyed() { return mDestroyed; } private void processPendingInfoBars() { if (mAnimation != null || mInfoBarTransitions.isEmpty()) return; // Start animating what has to be animated. InfoBarTransitionInfo info = mInfoBarTransitions.remove(); View toShow = info.toShow; ContentWrapperView targetView; addToParentView(); if (info.animationType == AnimationHelper.ANIMATION_TYPE_SHOW) { targetView = info.target.getContentWrapper(true); assert mInfoBars.contains(info.target); toShow = targetView.detachCurrentView(); addView(targetView, mInfoBarsOnTop ? getChildCount() : 0, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } else { targetView = info.target.getContentWrapper(false); } // Kick off the animation. mAnimation = new AnimationHelper(this, targetView, info.target, toShow, info.animationType); mAnimation.start(); } // Called by the tab when it has started loading a new page. public void onPageStarted(String url) { LinkedList<InfoBar> barsToRemove = new LinkedList<InfoBar>(); for (InfoBar infoBar : mInfoBars) { if (infoBar.shouldExpire(url)) { barsToRemove.add(infoBar); } } for (InfoBar infoBar : barsToRemove) { infoBar.dismissJavaOnlyInfoBar(); } } /** * Returns the id of the tab we are associated with. */ public int getTabId() { return mTabId; } public void destroy() { mDestroyed = true; removeAllViews(); if (mNativeInfoBarContainer != 0) { nativeDestroy(mNativeInfoBarContainer); } mInfoBarTransitions.clear(); } /** * @return all of the InfoBars held in this container. */ @VisibleForTesting public ArrayList<InfoBar> getInfoBars() { return mInfoBars; } /** * Dismisses all {@link AutoLoginInfoBar}s in this {@link InfoBarContainer} that are for * {@code accountName} and {@code authToken}. This also resets all {@link InfoBar}s that are * for a different request. * @param accountName The name of the account request is being accessed for. * @param authToken The authentication token access is being requested for. * @param success Whether or not the authentication attempt was successful. * @param result The resulting token for the auto login request (ignored if {@code success} is * {@code false}. */ public void processAutoLogin(String accountName, String authToken, boolean success, String result) { mAutoLoginDelegate.dismissAutoLogins(accountName, authToken, success, result); } /** * Dismiss all auto logins infobars without processing any result. */ public void dismissAutoLoginInfoBars() { mAutoLoginDelegate.dismissAutoLogins("", "", false, ""); } public void prepareTransition(View toShow) { if (toShow != null) { // In order to animate the addition of the infobar, we need a layout first. // Attach the child to invisible layout so that we can get measurements for it without // moving everything in the real container. ViewGroup parent = (ViewGroup) toShow.getParent(); if (parent != null) parent.removeView(toShow); assert mAnimationSizer.getParent() == null; mParentView.addView(mAnimationSizer, createLayoutParams()); mAnimationSizer.addView(toShow, 0, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mAnimationSizer.requestLayout(); } } public void startTransition() { if (mInfoBarsOnTop) { // We need to clip this view to its bounds while it is animated because the layout's // z-ordering puts it on top of other infobars as it's being animated. ApiCompatibilityUtils.postInvalidateOnAnimation(this); } } /** * Finishes off whatever animation is running. */ public void finishTransition() { assert mAnimation != null; // If the InfoBar was hidden, get rid of its View entirely. if (mAnimation.getAnimationType() == AnimationHelper.ANIMATION_TYPE_HIDE) { removeView(mAnimation.getTarget()); } // Reset all translations and put everything where they need to be. for (int i = 0; i < getChildCount(); ++i) { View view = getChildAt(i); view.setTranslationY(0); } requestLayout(); // If there are no infobars shown, there is no need to keep the infobar container in the // view hierarchy. if (getChildCount() == 0) { removeFromParentView(); } if (mAnimationSizer.getParent() != null) { ((ViewGroup) mAnimationSizer.getParent()).removeView(mAnimationSizer); } // Notify interested parties and move on to the next animation. if (mAnimationListener != null) { mAnimationListener.notifyAnimationFinished(mAnimation.getAnimationType()); } mAnimation = null; processPendingInfoBars(); } /** * Searches a given view's child views for an instance of {@link InfoBarContainer}. * * @param parentView View to be searched for * @return {@link InfoBarContainer} instance if it's one of the child views; * otherwise {@code null}. */ public static InfoBarContainer childViewOf(ViewGroup parentView) { for (int i = 0; i < parentView.getChildCount(); i++) { if (parentView.getChildAt(i) instanceof InfoBarContainer) { return (InfoBarContainer) parentView.getChildAt(i); } } return null; } public long getNative() { return mNativeInfoBarContainer; } private native long nativeInit(WebContents webContents, AutoLoginDelegate autoLoginDelegate); private native void nativeDestroy(long nativeInfoBarContainerAndroid); }
package com.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.BackgroundEditorHighlighter; import com.intellij.codeHighlighting.HighlightingPass; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.intention.impl.IntentionHintComponent; import com.intellij.codeInsight.problems.WolfTheProblemSolverImpl; import com.intellij.ide.highlighter.custom.impl.CustomFileType; import com.intellij.ide.projectView.impl.nodes.PackageUtil; import com.intellij.ide.todo.TodoConfiguration; import com.intellij.j2ee.extResources.ExternalResourceListener; import com.intellij.j2ee.openapi.ex.ExternalResourceManagerEx; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.ant.config.AntBuildFile; import com.intellij.lang.ant.config.AntConfiguration; import com.intellij.lang.ant.config.AntConfigurationListener; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.command.CommandAdapter; import com.intellij.openapi.command.CommandEvent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.colors.EditorColorsListener; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.EditorEventMulticasterEx; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerAdapter; import com.intellij.openapi.roots.ModuleRootEvent; import com.intellij.openapi.roots.ModuleRootListener; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vcs.ProjectLevelVcsManager; import com.intellij.openapi.vfs.*; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.IdeFrame; import com.intellij.problems.WolfTheProblemSolver; import com.intellij.profile.Profile; import com.intellij.profile.ProfileChangeAdapter; import com.intellij.profile.codeInspection.InspectionProfileManager; import com.intellij.psi.*; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.util.Alarm; import com.intellij.util.SmartList; import com.intellij.util.concurrency.Semaphore; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.*; /** * This class also controls the auto-reparse and auto-hints. */ public class DaemonCodeAnalyzerImpl extends DaemonCodeAnalyzer implements JDOMExternalizable, ProjectComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl"); private static final Key<HighlightInfo[]> HIGHLIGHTS_IN_EDITOR_DOCUMENT_KEY = Key.create("DaemonCodeAnalyzerImpl.HIGHLIGHTS_IN_EDITOR_DOCUMENT_KEY"); private static final Key<LineMarkerInfo[]> MARKERS_IN_EDITOR_DOCUMENT_KEY = Key.create("DaemonCodeAnalyzerImpl.MARKERS_IN_EDITOR_DOCUMENT_KEY"); private final Project myProject; private final DaemonCodeAnalyzerSettings mySettings; private EditorTracker myEditorTracker; private final DaemonProgress myUpdateProgress = new DaemonProgress(); private final Semaphore myUpdateThreadSemaphore = new Semaphore(); private final Runnable myUpdateRunnable = createUpdateRunnable(); private final Alarm myAlarm = new Alarm(); private boolean myUpdateByTimerEnabled = true; private final Set<VirtualFile> myDisabledHintsFiles = new THashSet<VirtualFile>(); private final Set<PsiFile> myDisabledHighlightingFiles = new THashSet<PsiFile>(); private final FileStatusMap myFileStatusMap; private StatusBarUpdater myStatusBarUpdater; private DaemonCodeAnalyzerSettings myLastSettings; private final MyCommandListener myCommandListener = new MyCommandListener(); private final MyApplicationListener myApplicationListener = new MyApplicationListener(); private final EditorColorsListener myEditorColorsListener = new MyEditorColorsListener(); private final AnActionListener myAnActionListener = new MyAnActionListener(); private final PropertyChangeListener myTodoListener = new MyTodoListener(); private final ExternalResourceListener myExternalResourceListener = new MyExternalResourceListener(); private final AntConfigurationListener myAntConfigurationListener = new MyAntConfigurationListener(); private final EditorMouseMotionListener myEditorMouseMotionListener = new MyEditorMouseMotionListener(); private final EditorMouseListener myEditorMouseListener = new MyEditorMouseListener(); private final ProfileChangeAdapter myProfileChangeListener = new MyProfileChangeListener(); private final WindowFocusListener myIdeFrameFocusListener = new MyWindowFocusListener(); private DocumentListener myDocumentListener; private CaretListener myCaretListener; private ErrorStripeHandler myErrorStripeHandler; //private long myUpdateStartTime; private boolean myEscPressed; private EditorFactoryListener myEditorFactoryListener; private boolean myShowPostIntentions = true; private IntentionHintComponent myLastIntentionHint; private boolean myDisposed; private boolean myInitialized; private boolean myIsFrameFocused = true; @NonNls private static final String DISABLE_HINTS_TAG = "disable_hints"; @NonNls private static final String FILE_TAG = "file"; @NonNls private static final String URL_ATT = "url"; private boolean cutOperationJustHappened; private VirtualFileAdapter myVirtualFileListener; protected DaemonCodeAnalyzerImpl(Project project, DaemonCodeAnalyzerSettings daemonCodeAnalyzerSettings) { myProject = project; mySettings = daemonCodeAnalyzerSettings; myLastSettings = (DaemonCodeAnalyzerSettings)mySettings.clone(); myFileStatusMap = new FileStatusMap(myProject); } @NotNull public String getComponentName() { return "DaemonCodeAnalyzer"; } public void initComponent() { } public void disposeComponent() { myFileStatusMap.markAllFilesDirty(); dispose(); } public EditorTracker getEditorTracker() { return myEditorTracker; } public void projectOpened() { EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster(); myDocumentListener = new DocumentAdapter() { public void documentChanged(DocumentEvent e) { stopProcess(true); UpdateHighlightersUtil.updateHighlightersByTyping(myProject, e); } }; eventMulticaster.addDocumentListener(myDocumentListener); myCaretListener = new CaretListener() { public void caretPositionChanged(CaretEvent e) { stopProcess(true); } }; eventMulticaster.addCaretListener(myCaretListener); eventMulticaster.addEditorMouseMotionListener(myEditorMouseMotionListener); eventMulticaster.addEditorMouseListener(myEditorMouseListener); myEditorTracker = createEditorTracker(); myEditorTracker.addEditorTrackerListener(new EditorTrackerListener() { public void activeEditorsChanged(final Editor[] editors) { if (editors.length > 0) { myIsFrameFocused = true; // Happens when debugger evaluation window gains focus out of main frame. } stopProcess(true); } }); myEditorFactoryListener = new EditorFactoryAdapter() { public void editorCreated(EditorFactoryEvent event) { Editor editor = event.getEditor(); Document document = editor.getDocument(); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (file != null) { ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeRenderer( new RefreshStatusRenderer(myProject, DaemonCodeAnalyzerImpl.this, document, file)); } } }; EditorFactory.getInstance().addEditorFactoryListener(myEditorFactoryListener); PsiManager.getInstance(myProject).addPsiTreeChangeListener(new PsiChangeHandler(myProject, this)); ProjectRootManager.getInstance(myProject).addModuleRootListener(new ModuleRootListener() { public void beforeRootsChange(ModuleRootEvent event) { } public void rootsChanged(ModuleRootEvent event) { final FileEditor[] editors = FileEditorManager.getInstance(myProject).getSelectedEditors(); if (editors != null) { for (FileEditor fileEditor : editors) { if (fileEditor instanceof TextEditor) { final Editor editor = ((TextEditor)fileEditor).getEditor(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myProject.isDisposed()) return; final Document document = editor.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeRenderer(new RefreshStatusRenderer(myProject, DaemonCodeAnalyzerImpl.this, document, psiFile)); } }, ModalityState.stateForComponent(editor.getComponent())); } } } } }); CommandProcessor.getInstance().addCommandListener(myCommandListener); ApplicationManager.getApplication().addApplicationListener(myApplicationListener); EditorColorsManager.getInstance().addEditorColorsListener(myEditorColorsListener); InspectionProfileManager.getInstance().addProfileChangeListener(myProfileChangeListener); TodoConfiguration.getInstance().addPropertyChangeListener(myTodoListener); ActionManagerEx.getInstanceEx().addAnActionListener(myAnActionListener); ExternalResourceManagerEx.getInstanceEx().addExteralResourceListener(myExternalResourceListener); myVirtualFileListener = new VirtualFileAdapter() { public void propertyChanged(VirtualFilePropertyEvent event) { if (VirtualFile.PROP_NAME.equals(event.getPropertyName())) { restart(); PsiFile psiFile = PsiManager.getInstance(myProject).findFile(event.getFile()); if (psiFile != null && !isHighlightingAvailable(psiFile)) { Document document = FileDocumentManager.getInstance().getCachedDocument(event.getFile()); if (document != null) { // highlight markers no more UpdateHighlightersUtil.setHighlightersToEditor(myProject, document, 0, document.getTextLength(), Collections.<HighlightInfo>emptyList(), UpdateHighlightersUtil.NORMAL_HIGHLIGHTERS_GROUP); } } } } }; VirtualFileManager.getInstance().addVirtualFileListener(myVirtualFileListener); if (myProject.hasComponent(AntConfiguration.class)) { AntConfiguration.getInstance(myProject).addAntConfigurationListener(myAntConfigurationListener); } myStatusBarUpdater = new StatusBarUpdater(myProject); myErrorStripeHandler = new ErrorStripeHandler(myProject); ((EditorEventMulticasterEx)eventMulticaster).addErrorStripeListener(myErrorStripeHandler); ProjectManager.getInstance().addProjectManagerListener( myProject, new ProjectManagerAdapter() { public void projectClosing(Project project) { dispose(); } } ); IdeFrame frame = ((WindowManagerEx)WindowManager.getInstance()).getFrame(myProject); if (frame != null) { frame.addWindowFocusListener(myIdeFrameFocusListener); } myInitialized = true; } public void projectClosed() { } private void dispose() { if (myDisposed) return; EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster(); eventMulticaster.removeDocumentListener(myDocumentListener); eventMulticaster.removeCaretListener(myCaretListener); eventMulticaster.removeEditorMouseMotionListener(myEditorMouseMotionListener); eventMulticaster.removeEditorMouseListener(myEditorMouseListener); EditorFactory.getInstance().removeEditorFactoryListener(myEditorFactoryListener); CommandProcessor.getInstance().removeCommandListener(myCommandListener); ApplicationManager.getApplication().removeApplicationListener(myApplicationListener); EditorColorsManager.getInstance().removeEditorColorsListener(myEditorColorsListener); InspectionProfileManager.getInstance().removeProfileChangeListener(myProfileChangeListener); TodoConfiguration.getInstance().removePropertyChangeListener(myTodoListener); ActionManagerEx.getInstanceEx().removeAnActionListener(myAnActionListener); ExternalResourceManagerEx.getInstanceEx().removeExternalResourceListener(myExternalResourceListener); VirtualFileManager.getInstance().removeVirtualFileListener(myVirtualFileListener); if (myProject.hasComponent(AntConfiguration.class)) { AntConfiguration.getInstance(myProject).removeAntConfigurationListener(myAntConfigurationListener); } if (myStatusBarUpdater != null) myStatusBarUpdater.dispose(); if (myEditorTracker != null) myEditorTracker.dispose(); ((EditorEventMulticasterEx)eventMulticaster).removeErrorStripeListener(myErrorStripeHandler); // clear dangling references to PsiFiles/Documents. SCR#10358 myFileStatusMap.markAllFilesDirty(); myDisposed = true; stopProcess(false); myUpdateThreadSemaphore.waitFor(); myLastSettings = null; IdeFrame frame = ((WindowManagerEx)WindowManager.getInstance()).getFrame(myProject); if (frame != null) { frame.removeWindowFocusListener(myIdeFrameFocusListener); } } public void settingsChanged() { DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance(); if (settings.isCodeHighlightingChanged(myLastSettings)) { restart(); } myLastSettings = (DaemonCodeAnalyzerSettings)settings.clone(); } public void updateVisibleHighlighters(Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); if (ApplicationManager.getApplication().isUnitTestMode()) return; setShowPostIntentions(false); TextEditor textEditor = TextEditorProvider.getInstance().getTextEditor(editor); BackgroundEditorHighlighter highlighter = textEditor.getBackgroundHighlighter(); if (highlighter == null) return; updateHighlighters(textEditor, new LinkedHashSet<HighlightingPass>(Arrays.asList(highlighter.createPassesForVisibleArea())), null); } private void updateAll(FileEditor editor, Runnable postRunnable) { ApplicationManager.getApplication().assertIsDispatchThread(); if (LOG.isDebugEnabled()) { /* TODO: PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument()); LOG.debug("updateAll for " + file); */ } //myUpdateStartTime = System.currentTimeMillis(); //Statistics.clear(); boolean editorHiddenByModelDialog = ModalityState.current().dominates(ModalityState.stateForComponent(editor.getComponent())); if (editorHiddenByModelDialog) { stopProcess(true); return; } BackgroundEditorHighlighter highlighter = editor.getBackgroundHighlighter(); final HighlightingPass[] passes = highlighter == null ? HighlightingPass.EMPTY_ARRAY : highlighter.createPassesForEditor(); updateHighlighters(editor, new LinkedHashSet<HighlightingPass>(Arrays.asList(passes)), postRunnable); } public void setUpdateByTimerEnabled(boolean value) { myUpdateByTimerEnabled = value; stopProcess(true); } public void setImportHintsEnabled(PsiFile file, boolean value) { VirtualFile vFile = file.getVirtualFile(); if (value) { myDisabledHintsFiles.remove(vFile); stopProcess(true); } else { myDisabledHintsFiles.add(vFile); HintManager.getInstance().hideAllHints(); } } public void resetImportHintsEnabledForProject() { myDisabledHintsFiles.clear(); } public void setHighlightingEnabled(PsiFile file, boolean value) { if (value) { myDisabledHighlightingFiles.remove(file); } else { myDisabledHighlightingFiles.add(file); } } public boolean isHighlightingAvailable(PsiFile file) { if (myDisabledHighlightingFiles.contains(file)) return false; if (!file.isPhysical()) return false; if (file instanceof PsiCompiledElement) return false; final FileType fileType = file.getFileType(); if (fileType == StdFileTypes.GUI_DESIGNER_FORM){ return true; } // To enable T.O.D.O. highlighting return !(file instanceof PsiPlainTextFile) || fileType instanceof CustomFileType; } public boolean isImportHintsEnabled(PsiFile file) { return isAutohintsAvailable(file) && !myDisabledHintsFiles.contains(file.getVirtualFile()); } public boolean isAutohintsAvailable(PsiFile file) { return isHighlightingAvailable(file) && !(file instanceof PsiCompiledElement); } public void restart() { myFileStatusMap.markAllFilesDirty(); stopProcess(true); } public boolean isErrorAnalyzingFinished(PsiFile file) { if (myDisposed) return false; Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); if (document == null) return false; if (document.getModificationStamp() != file.getModificationStamp()) return false; return myFileStatusMap.getFileDirtyScope(document, FileStatusMap.NORMAL_HIGHLIGHTERS) == null; } public boolean isInspectionCompleted(PsiFile file) { if (file instanceof PsiCompiledElement) return true; Document document = PsiDocumentManager.getInstance(myProject).getDocument(file); if (document.getModificationStamp() != file.getModificationStamp()) return false; return myFileStatusMap.getFileDirtyScope(document, FileStatusMap.LOCAL_INSPECTIONS) == null; } public FileStatusMap getFileStatusMap() { return myFileStatusMap; } public DaemonProgress getUpdateProgress() { return myUpdateProgress; } public void stopProcess(boolean toRestartAlarm) { myAlarm.cancelAllRequests(); if (toRestartAlarm && !myDisposed && myInitialized && myIsFrameFocused) { //LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode()); myAlarm.addRequest(myUpdateRunnable, mySettings.AUTOREPARSE_DELAY); } myUpdateProgress.cancel(); } @Nullable public static HighlightInfo[] getHighlights(Document document, Project project) { LOG.assertTrue(ApplicationManager.getApplication().isReadAccessAllowed()); MarkupModel markup = document.getMarkupModel(project); return markup.getUserData(HIGHLIGHTS_IN_EDITOR_DOCUMENT_KEY); } @NotNull public static HighlightInfo[] getHighlights(Document document, HighlightSeverity minSeverity, Project project) { return getHighlights(document, minSeverity, project, Integer.MIN_VALUE, Integer.MAX_VALUE); } @NotNull public static HighlightInfo[] getHighlights(Document document, HighlightSeverity minSeverity, Project project, int startOffset, int endOffset) { LOG.assertTrue(ApplicationManager.getApplication().isReadAccessAllowed()); HighlightInfo[] highlights = getHighlights(document, project); if (highlights == null) return HighlightInfo.EMPTY_ARRAY; ArrayList<HighlightInfo> array = new ArrayList<HighlightInfo>(); for (HighlightInfo info : highlights) { if (info.getSeverity().compareTo(minSeverity) >= 0 && info.startOffset >= startOffset && info.endOffset <= endOffset) { array.add(info); } } return array.toArray(new HighlightInfo[array.size()]); } @Nullable public HighlightInfo findHighlightByOffset(Document document, int offset, boolean includeFixRange) { HighlightInfo[] highlights = getHighlights(document, myProject); if (highlights == null) return null; List<HighlightInfo> foundInfoList = new SmartList<HighlightInfo>(); for (HighlightInfo info : highlights) { if (info.highlighter == null || !info.highlighter.isValid()) continue; int startOffset = info.highlighter.getStartOffset(); int endOffset = info.highlighter.getEndOffset(); if (info.isAfterEndOfLine) { startOffset += 1; endOffset += 1; } if (startOffset > offset || offset > endOffset) { if (!includeFixRange) continue; if (info.fixMarker == null || !info.fixMarker.isValid()) continue; startOffset = info.fixMarker.getStartOffset(); endOffset = info.fixMarker.getEndOffset(); if (info.isAfterEndOfLine) { startOffset += 1; endOffset += 1; } if (startOffset > offset || offset > endOffset) continue; } if (!foundInfoList.isEmpty()) { HighlightInfo foundInfo = foundInfoList.get(0); if (foundInfo.getSeverity().compareTo(info.getSeverity()) < 0) { foundInfoList.clear(); } else if (info.getSeverity().compareTo(foundInfo.getSeverity()) < 0) { continue; } } foundInfoList.add(info); } if (foundInfoList.isEmpty()) return null; if (foundInfoList.size() == 1) return foundInfoList.get(0); return new HighlightInfoComposite(foundInfoList); } public static void setHighlights(Document document, HighlightInfo[] highlights, Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); MarkupModel markup = document.getMarkupModel(project); highlights = stripWarningsCoveredByErrors(highlights, markup); markup.putUserData(HIGHLIGHTS_IN_EDITOR_DOCUMENT_KEY, highlights); DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project); if (codeAnalyzer instanceof DaemonCodeAnalyzerImpl && ((DaemonCodeAnalyzerImpl)codeAnalyzer).myStatusBarUpdater != null) { ((DaemonCodeAnalyzerImpl)codeAnalyzer).myStatusBarUpdater.updateStatus(); } } @NotNull private static HighlightInfo[] stripWarningsCoveredByErrors(HighlightInfo[] highlights, MarkupModel markup) { List<HighlightInfo> all = new ArrayList<HighlightInfo>(Arrays.asList(highlights)); List<HighlightInfo> errors = new ArrayList<HighlightInfo>(); for (HighlightInfo highlight : highlights) { if (highlight.getSeverity() == HighlightSeverity.ERROR) { errors.add(highlight); } } for (HighlightInfo highlight : highlights) { if (highlight.getSeverity().myVal < HighlightSeverity.ERROR.myVal && highlight.getSeverity().myVal > 0) { for (HighlightInfo errorInfo : errors) { if (isCoveredBy(highlight, errorInfo)) { all.remove(highlight); RangeHighlighter highlighter = highlight.highlighter; if (highlighter != null && highlighter.isValid()) { markup.removeHighlighter(highlighter); } break; } } } } return all.size() < highlights.length ? all.toArray(new HighlightInfo[all.size()]) : highlights; } private static boolean isCoveredBy(HighlightInfo testInfo, HighlightInfo coveringCandidate) { return testInfo.startOffset <= coveringCandidate.endOffset && testInfo.endOffset >= coveringCandidate.startOffset; } @Nullable public static LineMarkerInfo[] getLineMarkers(Document document, Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); MarkupModel markup = document.getMarkupModel(project); return markup.getUserData(MARKERS_IN_EDITOR_DOCUMENT_KEY); } public static void setLineMarkers(Document document, LineMarkerInfo[] lineMarkers, Project project) { ApplicationManager.getApplication().assertIsDispatchThread(); MarkupModel markup = document.getMarkupModel(project); markup.putUserData(MARKERS_IN_EDITOR_DOCUMENT_KEY, lineMarkers); } public void setShowPostIntentions(boolean status) { myShowPostIntentions = status; } public boolean showPostIntentions() { return myShowPostIntentions; } public void setLastIntentionHint(IntentionHintComponent hintComponent) { myLastIntentionHint = hintComponent; } public IntentionHintComponent getLastIntentionHint() { return myLastIntentionHint; } private void updateHighlighters(final FileEditor editor, final Set<? extends HighlightingPass> passesToPerform, final Runnable postRunnable) { ApplicationManager.getApplication().assertIsDispatchThread(); if (myUpdateProgress.isRunning()) return; if (passesToPerform.isEmpty()) { if (postRunnable != null) postRunnable.run(); return; } final HighlightingPass daemonPass = passesToPerform.iterator().next(); Runnable postRunnable1 = new Runnable() { public void run() { final boolean wasCanceled = myUpdateProgress.isCanceled(); final boolean wasRunning = myUpdateProgress.isRunning(); myUpdateThreadSemaphore.up(); if (editor != null) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myDisposed) return; if (!wasCanceled || wasRunning) { if (daemonPass != null && editor.getComponent().isDisplayable()) { daemonPass.applyInformationToEditor(); } passesToPerform.remove(daemonPass); updateHighlighters(editor, passesToPerform, postRunnable); } } }, ModalityState.stateForComponent(editor.getComponent())); } } }; UpdateThread updateThread; synchronized (myUpdateProgress) { if (myUpdateProgress.isRunning()) return; //Last check to be sure we don't launch 2 threads updateThread = new UpdateThread(daemonPass, myProject, postRunnable1); //After the call myUpdateProgress.isRunning() } myUpdateThreadSemaphore.down(); updateThread.start(); } public void writeExternal(Element parentNode) throws WriteExternalException { Element disableHintsElement = new Element(DISABLE_HINTS_TAG); parentNode.addContent(disableHintsElement); ArrayList<String> array = new ArrayList<String>(); for (VirtualFile file : myDisabledHintsFiles) { if (file.isValid()) { array.add(file.getUrl()); } } Collections.sort(array); for (String url : array) { Element fileElement = new Element(FILE_TAG); fileElement.setAttribute(URL_ATT, url); disableHintsElement.addContent(fileElement); } } public void readExternal(Element parentNode) throws InvalidDataException { myDisabledHintsFiles.clear(); Element element = parentNode.getChild(DISABLE_HINTS_TAG); if (element != null) { for (Object o : element.getChildren(FILE_TAG)) { Element e = (Element)o; String url = e.getAttributeValue(URL_ATT); if (url != null) { VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file != null) { myDisabledHintsFiles.add(file); } } } } } boolean canChangeFileSilently(PsiFile file) { if (cutOperationJustHappened) return false; VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return false; Project project = file.getProject(); if (!PackageUtil.projectContainsFile(project, virtualFile, false)) return false; AbstractVcs activeVcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(virtualFile); if (activeVcs == null) return true; FileStatus status = FileStatusManager.getInstance(project).getStatus(virtualFile); return status != FileStatus.NOT_CHANGED; } private class MyApplicationListener extends ApplicationAdapter { public void beforeWriteActionStart(Object action) { if (!myUpdateProgress.isRunning()) return; if (myUpdateProgress.isCanceled()) return; if (LOG.isDebugEnabled()) { LOG.debug("cancelling code highlighting by write action:" + action); } stopProcess(false); } public void writeActionFinished(Object action) { stopProcess(true); } } private class MyCommandListener extends CommandAdapter { private final String myCutActionName = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_CUT).getTemplatePresentation().getText(); public void commandStarted(CommandEvent event) { cutOperationJustHappened = myCutActionName.equals(event.getCommandName()); if (!myUpdateProgress.isRunning()) return; if (myUpdateProgress.isCanceled()) return; if (LOG.isDebugEnabled()) { LOG.debug("cancelling code highlighting by command:" + event.getCommand()); } stopProcess(false); } public void commandFinished(CommandEvent event) { if (!myEscPressed) { stopProcess(true); } else { myEscPressed = false; } } } private class MyEditorColorsListener implements EditorColorsListener { public void globalSchemeChange(EditorColorsScheme scheme) { restart(); } } private class MyTodoListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { if (TodoConfiguration.PROP_TODO_PATTERNS.equals(evt.getPropertyName())) { restart(); } } } private class MyProfileChangeListener extends ProfileChangeAdapter{ public void profileChanged(Profile profile) { restart(); } public void profileActivated(NamedScope scope, Profile oldProfile, Profile profile) { restart(); } } private class MyAnActionListener implements AnActionListener { public void beforeActionPerformed(AnAction action, DataContext dataContext) { AnAction escapeAction = ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE); if (action != escapeAction) { stopProcess(true); myEscPressed = false; } else { myEscPressed = true; } } public void beforeEditorTyping(char c, DataContext dataContext) { stopProcess(true); myEscPressed = false; } } private class MyExternalResourceListener implements ExternalResourceListener { public void externalResourceChanged() { restart(); } } private class MyAntConfigurationListener implements AntConfigurationListener { public void buildFileChanged(final AntBuildFile buildFile) { restart(); } public void buildFileAdded(final AntBuildFile buildFile) { restart(); } public void buildFileRemoved(final AntBuildFile buildFile) { restart(); } } private static class WolfPass implements HighlightingPass { private Project myProject; public WolfPass(final Project project) { myProject = project; } public void collectInformation(ProgressIndicator progress) { final WolfTheProblemSolver solver = WolfTheProblemSolver.getInstance(myProject); if (solver instanceof WolfTheProblemSolverImpl) { ((WolfTheProblemSolverImpl)solver).startCheckingIfVincentSolvedProblemsYet(progress); } } public void applyInformationToEditor() { } } private Runnable createUpdateRunnable() { return new Runnable() { public void run() { if (LOG.isDebugEnabled()) { LOG.debug("update runnable (myUpdateByTimerEnabled = " + myUpdateByTimerEnabled + ")"); } if (!myUpdateByTimerEnabled) return; final FileEditor[] activeEditors = getSelectedEditors(); if (activeEditors.length == 0) { if (LOG.isDebugEnabled()) { LOG.debug("no active editors"); } return; } class CallWolfRunnable implements Runnable { public void run() { updateHighlighters(null, Collections.singleton(new WolfPass(myProject)), null); } } class UpdateEditorRunnable implements Runnable { private int editorIndex; UpdateEditorRunnable(int editorIndex) { this.editorIndex = editorIndex; } public void run() { Runnable postRunnable = editorIndex < activeEditors.length - 1 ? new UpdateEditorRunnable(editorIndex + 1) : new CallWolfRunnable(); updateAll(activeEditors[editorIndex], postRunnable); } } new UpdateEditorRunnable(0).run(); } }; } private FileEditor[] getSelectedEditors() { // Editors in modal context Editor[] editors = myEditorTracker.getActiveEditors(); FileEditor[] fileEditors = new FileEditor[editors.length]; if (editors.length > 0) { for (int i = 0; i < fileEditors.length; i++) { fileEditors[i] = TextEditorProvider.getInstance().getTextEditor(editors[i]); } } if (ApplicationManager.getApplication().getCurrentModalityState() != ModalityState.NON_MMODAL) { return fileEditors; } final FileEditor[] tabEditors = FileEditorManager.getInstance(myProject).getSelectedEditors(); if (fileEditors.length == 0) return tabEditors; // Editors in tabs. Set<FileEditor> common = new HashSet<FileEditor>(Arrays.asList(fileEditors)); common.addAll(Arrays.asList(tabEditors)); return common.toArray(new FileEditor[common.size()]); } /** * @fabrique used in fabrique * */ private EditorTracker createEditorTracker() { return new EditorTracker(myProject); } private static class MyEditorMouseListener extends EditorMouseAdapter{ public void mouseExited(EditorMouseEvent e) { DaemonTooltipUtil.cancelTooltips(); } } private class MyEditorMouseMotionListener implements EditorMouseMotionListener { public void mouseMoved(EditorMouseEvent e) { Editor editor = e.getEditor(); if (myProject != editor.getProject()) return; boolean shown = false; try { LogicalPosition pos = editor.xyToLogicalPosition(e.getMouseEvent().getPoint()); if (e.getArea() == EditorMouseEventArea.EDITING_AREA) { int offset = editor.logicalPositionToOffset(pos); if (editor.offsetToLogicalPosition(offset).column != pos.column) return; // we are in virtual space HighlightInfo info = findHighlightByOffset(editor.getDocument(), offset, false); if (info == null || info.description == null) return; DaemonTooltipUtil.showInfoTooltip(info, editor, offset); shown = true; } } finally { if (!shown) { DaemonTooltipUtil.cancelTooltips(); } } } public void mouseDragged(EditorMouseEvent e) { HintManager.getInstance().getTooltipController().cancelTooltips(); } } private class MyWindowFocusListener implements WindowFocusListener { public void windowGainedFocus(WindowEvent e) { if (LOG.isDebugEnabled()) { LOG.debug("windowGainedFocus for IdeFrame"); } myIsFrameFocused = true; stopProcess(true); } public void windowLostFocus(WindowEvent e) { if (LOG.isDebugEnabled()) { LOG.debug("windowLostFocus for IdeFrame"); } myIsFrameFocused = false; stopProcess(false); } } }
package com.malhartech.api.util; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.module.SimpleModule; import org.codehaus.jackson.map.ser.impl.RawSerializer; /** * * @author David Yan <davidyan@malhar-inc.com> */ @Provider @Produces(MediaType.APPLICATION_JSON) public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper> { private ObjectMapper objectMapper = new ObjectMapper(); public JacksonObjectMapperProvider() { objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null)); module.addSerializer(ObjectMapperString.class, new RawSerializer<Object>(Object.class)); objectMapper.registerModule(module); } @Override public ObjectMapper getContext(Class<?> type) { return objectMapper; } }
package org.jboss.jca.common.util; import org.jboss.jca.common.api.ConnectionFactoryBuilder; import org.jboss.jca.fungal.deployers.DeployException; import javax.naming.Reference; import javax.naming.StringRefAddr; import javax.resource.spi.ManagedConnectionFactory; /** * Local only connection factory builder. * * @author <a href="mailto:smarlow@redhat.com">Scott Marlow</a> */ public class LocalConnectionFactoryBuilder implements ConnectionFactoryBuilder { private ManagedConnectionFactory mcf; private Object cf; private String name; /** * {@inheritDoc} */ public ConnectionFactoryBuilder setName(String name) { if (name == null || name.trim().equals("")) throw new IllegalArgumentException("Name is null"); this.name = name; return this; } /** * {@inheritDoc} */ public Reference build() throws DeployException { String className = cf.getClass().getName(); String name = this.name; Reference ref = new Reference( cf.getClass().getName(), new StringRefAddr("class", className), LocalApplicationServerJNDIHandler.class.getName(), null); ref.add(new StringRefAddr("name", name)); LocalApplicationServerJNDIHandler.register(name, className, this); return ref; } /** * {@inheritDoc} */ public ConnectionFactoryBuilder setManagedConnectionFactory(ManagedConnectionFactory mcf) { this.mcf = mcf; return this; } /** * {@inheritDoc} */ public ManagedConnectionFactory getManagedConnectionFactory() { return mcf; } /** * {@inheritDoc} */ public ConnectionFactoryBuilder setConnectionFactory(Object cf) { this.cf = cf; return this; } /** * {@inheritDoc} */ public Object getConnectionFactory() { return cf; } }
package com.yahoo.vespa.model.content.cluster; import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.model.test.TestDriver; import com.yahoo.searchdefinition.SearchBuilder; import com.yahoo.searchdefinition.parser.ParseException; import com.yahoo.vespa.config.search.core.PartitionsConfig; import com.yahoo.vespa.config.search.core.ProtonConfig; import com.yahoo.vespa.model.content.Content; import com.yahoo.vespa.model.search.IndexedSearchCluster; import com.yahoo.vespa.model.search.SearchDefinition; import com.yahoo.vespa.model.search.Dispatch; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import org.junit.Test; import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author Simon Thoresen Hult */ public class ClusterTest { @Test public void requireThatContentSearchIsApplied() throws ParseException { ContentCluster cluster = newContentCluster(joinLines("<search>", " <query-timeout>1.1</query-timeout>", " <visibility-delay>2.3</visibility-delay>", "</search>")); IndexedSearchCluster searchCluster = cluster.getSearch().getIndexed(); assertNotNull(searchCluster); assertEquals(1.1, searchCluster.getQueryTimeout(), 1E-6); assertEquals(2.3, searchCluster.getVisibilityDelay(), 1E-6); ProtonConfig proton = getProtonConfig(cluster); assertEquals(searchCluster.getVisibilityDelay(), proton.documentdb(0).visibilitydelay(), 1E-6); } @Test public void requireThatSearchCoverageIsApplied() throws ParseException { ContentCluster cluster = newContentCluster(joinLines("<search>", " <coverage>", " <minimum>0.11</minimum>", " <min-wait-after-coverage-factor>0.23</min-wait-after-coverage-factor>", " <max-wait-after-coverage-factor>0.58</max-wait-after-coverage-factor>", " </coverage>", "</search>")); assertEquals(1, cluster.getSearch().getIndexed().getTLDs().size()); for (Dispatch tld : cluster.getSearch().getIndexed().getTLDs()) { PartitionsConfig.Builder builder = new PartitionsConfig.Builder(); tld.getConfig(builder); PartitionsConfig config = new PartitionsConfig(builder); assertEquals(11.0, config.dataset(0).minimal_searchcoverage(), 1E-6); assertEquals(0.23, config.dataset(0).higher_coverage_minsearchwait(), 1E-6); assertEquals(0.58, config.dataset(0).higher_coverage_maxsearchwait(), 1E-6); assertEquals(2, config.dataset(0).searchablecopies()); assertTrue(config.dataset(0).useroundrobinforfixedrow()); } } @Test public void requireThatDispatchTuningIsApplied() throws ParseException { ContentCluster cluster = newContentCluster(joinLines("<search>", "</search>"), joinLines("<tuning>", "</tuning>")); assertEquals(1, cluster.getSearch().getIndexed().getTLDs().size()); for (Dispatch tld : cluster.getSearch().getIndexed().getTLDs()) { PartitionsConfig.Builder builder = new PartitionsConfig.Builder(); tld.getConfig(builder); PartitionsConfig config = new PartitionsConfig(builder); assertEquals(2, config.dataset(0).searchablecopies()); assertTrue(config.dataset(0).useroundrobinforfixedrow()); } } @Test public void requireThatVisibilityDelayIsZeroForGlobalDocumentType() throws ParseException { ContentCluster cluster = newContentCluster(joinLines("<search>", " <visibility-delay>2.3</visibility-delay>", "</search>"), true); ProtonConfig proton = getProtonConfig(cluster); assertEquals(0.0, proton.documentdb(0).visibilitydelay(), 1E-6); } private static ContentCluster newContentCluster(String contentSearchXml) throws ParseException { return newContentCluster(contentSearchXml, "", false); } private static ContentCluster newContentCluster(String contentSearchXml, String searchNodeTuningXml) throws ParseException { return newContentCluster(contentSearchXml, searchNodeTuningXml, false); } private static ContentCluster newContentCluster(String contentSearchXml, boolean globalDocType) throws ParseException { return newContentCluster(contentSearchXml, "", globalDocType); } private static ContentCluster newContentCluster(String contentSearchXml, String searchNodeTuningXml, boolean globalDocType) throws ParseException { ApplicationPackage app = new MockApplicationPackage.Builder() .withHosts(joinLines("<hosts>", " <host name='localhost'><alias>my_host</alias></host>", "</hosts>")) .withServices(joinLines("<services version='1.0'>", " <admin version='2.0'>", " <adminserver hostalias='my_host' />", " </admin>", " <content version='1.0'>", " <redundancy>3</redundancy>", " <documents>", " " + getDocumentXml(globalDocType), " </documents>", " <engine>", " <proton>", " <searchable-copies>2</searchable-copies>", searchNodeTuningXml, " </proton>", " </engine>", " <group>", " <node hostalias='my_host' distribution-key='0' />", " </group>", contentSearchXml, " </content>", "</services>")) .withSearchDefinitions(ApplicationPackageUtils.generateSearchDefinition("my_document")) .build(); List<Content> contents = new TestDriver().buildModel(app).getConfigModels(Content.class); assertEquals(1, contents.size()); return contents.get(0).getCluster(); } private static String getDocumentXml(boolean globalDocType) { return "<document mode='index' type='my_document' " + (globalDocType ? "global='true' " : "") + "/>"; } private static SearchDefinition newSearchDefinition(String name) throws ParseException { SearchBuilder builder = new SearchBuilder(); builder.importString("search " + name + " { document " + name + " { } }"); builder.build(); return new SearchDefinition(name, builder.getSearch(name)); } private static ProtonConfig getProtonConfig(ContentCluster cluster) { ProtonConfig.Builder builder = new ProtonConfig.Builder(); cluster.getSearch().getConfig(builder); return new ProtonConfig(builder); } }
package com.mapswithme.maps; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.mapswithme.maps.MapStorage.Index; public class DownloadUI extends ListActivity implements MapStorage.Listener { private static String TAG = "DownloadUI"; /// ListView adapter private static class DownloadAdapter extends BaseAdapter { /// @name Different row types. private static final int TYPE_GROUP = 0; private static final int TYPE_COUNTRY_GROUP = 1; private static final int TYPE_COUNTRY_IN_PROCESS = 2; private static final int TYPE_COUNTRY_READY = 3; private static final int TYPES_COUNT = 4; private LayoutInflater m_inflater; private Activity m_context; private int m_slotID = 0; private MapStorage m_storage; private static class CountryItem { public String m_name; public String m_flag; /// @see constants in MapStorage public int m_status; public CountryItem(MapStorage storage, Index idx) { m_name = storage.countryName(idx); m_flag = storage.countryFlag(idx); // The aapt can't process resources with name "do". Hack with renaming. if (m_flag.equals("do")) m_flag = "do_hack"; updateStatus(storage, idx); } public void updateStatus(MapStorage storage, Index idx) { if (idx.mCountry == -1 || (idx.mRegion == -1 && m_flag.length() == 0)) { // group and not a country m_status = MapStorage.GROUP; } else if (idx.mRegion == -1 && storage.countriesCount(idx) > 0) { // country with grouping m_status = MapStorage.COUNTRY; } else { // country or region without grouping m_status = storage.countryStatus(idx); } } public int getTextColor() { switch (m_status) { case MapStorage.ON_DISK: return 0xFF00A144; case MapStorage.ON_DISK_OUT_OF_DATE: return 0xFFFF69B4; case MapStorage.NOT_DOWNLOADED: return 0xFFFFFFFF; case MapStorage.DOWNLOAD_FAILED: return 0xFFFF0000; case MapStorage.DOWNLOADING: return 0xFF342BB6; case MapStorage.IN_QUEUE: return 0xFF5B94DE; default: return 0xFFFFFFFF; } } /// Get item type for list view representation; public int getType() { switch (m_status) { case MapStorage.GROUP: return TYPE_GROUP; case MapStorage.COUNTRY: return TYPE_COUNTRY_GROUP; case MapStorage.ON_DISK: case MapStorage.ON_DISK_OUT_OF_DATE: return TYPE_COUNTRY_READY; default : return TYPE_COUNTRY_IN_PROCESS; } } } private Index m_idx = new Index(); private CountryItem[] m_items = null; private String m_kb; private String m_mb; private AlertDialog.Builder m_alert; private DialogInterface.OnClickListener m_alertCancelHandler = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { dlg.dismiss(); } }; public DownloadAdapter(Activity context) { m_storage = MapStorage.getInstance(); m_context = context; m_inflater = (LayoutInflater) m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); m_kb = context.getString(R.string.kb); m_mb = context.getString(R.string.mb); m_alert = new AlertDialog.Builder(m_context); fillList(); } private String getSizeString(long size) { final long Mb = 1024 * 1024; if (size > Mb) { // do the correct rounding of Mb return (size + 512 * 1024) / Mb + " " + m_mb; } else { // get upper bound size for Kb return (size + 1023) / 1024 + " " + m_kb; } } /// Fill list for current m_group and m_country. private void fillList() { final int count = m_storage.countriesCount(m_idx); if (count > 0) { m_items = new CountryItem[count]; for (int i = 0; i < count; ++i) m_items[i] = new CountryItem(m_storage, m_idx.getChild(i)); } notifyDataSetChanged(); } /// Process list item click. public boolean onItemClick(int position) { if (m_items[position].m_status < 0) { // expand next level m_idx = m_idx.getChild(position); fillList(); return true; } else { processCountry(position); return false; } } private void showNotEnoughFreeSpaceDialog(String spaceNeeded, String countryName) { new AlertDialog.Builder(m_context) .setMessage(String.format(m_context.getString(R.string.free_space_for_country), spaceNeeded, countryName)) .setNegativeButton(m_context.getString(R.string.close), m_alertCancelHandler) .create() .show(); } static private long getFreeSpace() { StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); return (long)stat.getAvailableBlocks() * (long)stat.getBlockSize(); } private void processCountry(int position) { final Index idx = m_idx.getChild(position); final String name = m_items[position].m_name; // Get actual status here switch (m_storage.countryStatus(idx)) { case MapStorage.ON_DISK: // Confirm deleting m_alert .setTitle(name) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(android.R.string.cancel, m_alertCancelHandler) .create() .show(); break; case MapStorage.ON_DISK_OUT_OF_DATE: final long remoteSize = m_storage.countryRemoteSizeInBytes(idx); // Update or delete new AlertDialog.Builder(m_context) .setTitle(name) .setPositiveButton(m_context.getString(R.string.update_mb_or_kb, getSizeString(remoteSize)), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { final long size = remoteSize - m_storage.countryLocalSizeInBytes(idx); if (size > getFreeSpace()) showNotEnoughFreeSpaceDialog(getSizeString(size), name); else { m_storage.deleteCountry(idx); m_storage.downloadCountry(idx); } dlg.dismiss(); } }) .setNeutralButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(android.R.string.cancel, m_alertCancelHandler) .create() .show(); break; case MapStorage.NOT_DOWNLOADED: // Check for available free space final long size = m_storage.countryRemoteSizeInBytes(idx); if (size > getFreeSpace()) { showNotEnoughFreeSpaceDialog(getSizeString(size), name); } else { // Confirm downloading m_alert .setTitle(name) .setPositiveButton(m_context.getString(R.string.download_mb_or_kb, getSizeString(size)), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.downloadCountry(idx); dlg.dismiss(); } }) .setNegativeButton(android.R.string.cancel, m_alertCancelHandler) .create() .show(); } break; case MapStorage.DOWNLOAD_FAILED: // Do not confirm downloading if status is failed, just start it m_storage.downloadCountry(idx); break; case MapStorage.DOWNLOADING: // Confirm canceling m_alert .setTitle(name) .setPositiveButton(R.string.cancel_download, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dlg, int which) { m_storage.deleteCountry(idx); dlg.dismiss(); } }) .setNegativeButton(R.string.do_nothing, m_alertCancelHandler) .create() .show(); break; case MapStorage.IN_QUEUE: // Silently discard country from the queue m_storage.deleteCountry(idx); break; } // Actual status will be updated in "updateStatus" callback. } private void updateStatuses() { for (int i = 0; i < m_items.length; ++i) { final Index idx = m_idx.getChild(i); assert(idx.isValid()); if (idx.isValid()) m_items[i].updateStatus(m_storage, idx); } } /// @name Process routine from parent Activity. /// @return true If "back" was processed. public boolean onBackPressed() { // we are on the root level already - return if (m_idx.isRoot()) return false; // go to the parent level m_idx = m_idx.getParent(); fillList(); return true; } public void onResume(MapStorage.Listener listener) { if (m_slotID == 0) m_slotID = m_storage.subscribe(listener); // update actual statuses for items after resuming activity updateStatuses(); notifyDataSetChanged(); } public void onPause() { if (m_slotID != 0) { m_storage.unsubscribe(m_slotID); m_slotID = 0; } } @Override public int getItemViewType(int position) { return m_items[position].getType(); } @Override public int getViewTypeCount() { return TYPES_COUNT; } @Override public int getCount() { return (m_items != null ? m_items.length : 0); } @Override public CountryItem getItem(int position) { return m_items[position]; } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView m_name = null; public TextView m_summary = null; public ImageView m_flag = null; public ImageView m_map = null; void initFromView(View v) { m_name = (TextView) v.findViewById(R.id.title); m_summary = (TextView) v.findViewById(R.id.summary); m_flag = (ImageView) v.findViewById(R.id.country_flag); m_map = (ImageView) v.findViewById(R.id.show_country); } } /// Process "Map" button click in list view. private class MapClickListener implements OnClickListener { private int m_position; public MapClickListener(int position) { m_position = position; } @Override public void onClick(View v) { m_storage.showCountry(m_idx.getChild(m_position)); // close parent activity m_context.finish(); } } private String formatStringWithSize(int strID, int position) { return m_context.getString(strID, getSizeString(m_storage.countryLocalSizeInBytes(m_idx.getChild(position)))); } private String getSummary(int position) { int res = 0; switch (m_items[position].m_status) { case MapStorage.ON_DISK: return formatStringWithSize(R.string.downloaded_touch_to_delete, position); case MapStorage.ON_DISK_OUT_OF_DATE: return formatStringWithSize(R.string.downloaded_touch_to_update, position); case MapStorage.NOT_DOWNLOADED: res = R.string.touch_to_download; break; case MapStorage.DOWNLOAD_FAILED: res = R.string.download_has_failed; break; case MapStorage.DOWNLOADING: res = R.string.downloading; break; case MapStorage.IN_QUEUE: res = R.string.marked_for_downloading; break; default: return "An unknown error occured!"; } return m_context.getString(res); } private void setFlag(int position, ImageView v) { Resources res = m_context.getResources(); final int id = res.getIdentifier(m_items[position].m_flag, "drawable", "com.mapswithme.maps"); if (id > 0) v.setImageDrawable(res.getDrawable(id)); else Log.e(TAG, "Failed to get resource id from: " + m_items[position].m_flag); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); switch (getItemViewType(position)) { case TYPE_GROUP: convertView = m_inflater.inflate(R.layout.download_item_group, null); holder.initFromView(convertView); break; case TYPE_COUNTRY_GROUP: convertView = m_inflater.inflate(R.layout.download_item_country_group, null); holder.initFromView(convertView); break; case TYPE_COUNTRY_IN_PROCESS: convertView = m_inflater.inflate(R.layout.download_item_country, null); holder.initFromView(convertView); holder.m_map.setVisibility(Button.INVISIBLE); break; case TYPE_COUNTRY_READY: convertView = m_inflater.inflate(R.layout.download_item_country, null); holder.initFromView(convertView); break; } convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // set texts holder.m_name.setText(m_items[position].m_name); holder.m_name.setTextColor(m_items[position].getTextColor()); if (holder.m_summary != null) holder.m_summary.setText(getSummary(position)); // attach to "Map" button if needed if (holder.m_map != null && holder.m_map.getVisibility() == Button.VISIBLE) holder.m_map.setOnClickListener(new MapClickListener(position)); // show flag if needed if (holder.m_flag != null && holder.m_flag.getVisibility() == ImageView.VISIBLE) setFlag(position, holder.m_flag); return convertView; } /// Get list item position by index(g, c, r). /// @return -1 If no such item in display list. private int getItemPosition(Index idx) { if (m_idx.isChild(idx)) { final int position = idx.getPosition(); if (position >= 0 && position < m_items.length) return position; else Log.e(TAG, "Incorrect item position for: " + idx.toString()); } return -1; } public void onCountryStatusChanged(Index idx) { Log.d(TAG, "onCountryStatusChanged for index: " + idx.toString()); final int position = getItemPosition(idx); if (position != -1) { m_items[position].updateStatus(m_storage, idx); // use this hard reset, because of caching different ViewHolders according to item's type notifyDataSetChanged(); } } public void onCountryProgress(ListView list, Index idx, long current, long total) { final int position = getItemPosition(idx); if (position != -1) { assert(m_items[position].m_status == 3); // do update only one item's view; don't call notifyDataSetChanged View v = list.getChildAt(position - list.getFirstVisiblePosition()); if (v != null) { ViewHolder holder = (ViewHolder) v.getTag(); holder.m_summary.setText(String.format(m_context.getString(R.string.downloading_touch_to_cancel), current * 100 / total)); v.invalidate(); } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.downloader_list_view); setListAdapter(new DownloadAdapter(this)); } private DownloadAdapter getDA() { return (DownloadAdapter) getListView().getAdapter(); } @Override protected void onResume() { super.onResume(); getDA().onResume(this); } @Override protected void onPause() { super.onPause(); getDA().onPause(); } @Override public void onBackPressed() { if (getDA().onBackPressed()) { // scroll list view to the top setSelection(0); } else super.onBackPressed(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if (getDA().onItemClick(position)) { // scroll list view to the top setSelection(0); } } @Override public void onCountryStatusChanged(Index idx) { getDA().onCountryStatusChanged(idx); } @Override public void onCountryProgress(Index idx, long current, long total) { getDA().onCountryProgress(getListView(), idx, current, total); } }
package com.rnfs; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.util.Base64; import android.util.SparseArray; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.RCTNativeAppEventEmitter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.net.URL; import java.security.MessageDigest; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class RNFSManager extends ReactContextBaseJavaModule { private static final String RNFSDocumentDirectoryPath = "RNFSDocumentDirectoryPath"; private static final String RNFSExternalDirectoryPath = "RNFSExternalDirectoryPath"; private static final String RNFSExternalStorageDirectoryPath = "RNFSExternalStorageDirectoryPath"; private static final String RNFSPicturesDirectoryPath = "RNFSPicturesDirectoryPath"; private static final String RNFSTemporaryDirectoryPath = "RNFSTemporaryDirectoryPath"; private static final String RNFSCachesDirectoryPath = "RNFSCachesDirectoryPath"; private static final String RNFSExternalCachesDirectoryPath = "RNFSExternalCachesDirectoryPath"; private static final String RNFSDocumentDirectory = "RNFSDocumentDirectory"; private static final String RNFSFileTypeRegular = "RNFSFileTypeRegular"; private static final String RNFSFileTypeDirectory = "RNFSFileTypeDirectory"; private SparseArray<Downloader> downloaders = new SparseArray<Downloader>(); private SparseArray<Uploader> uploaders = new SparseArray<Uploader>(); private ReactApplicationContext reactContext; public RNFSManager(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNFSManager"; } private Uri getFileUri(String filepath) throws IORejectionException { Uri uri = Uri.parse(filepath); if (uri.getScheme() == null) { // No prefix, assuming that provided path is absolute path to file File file = new File(filepath); if (file.isDirectory()) { throw new IORejectionException("EISDIR", "EISDIR: illegal operation on a directory, read '" + filepath + "'"); } uri = Uri.parse("file://" + filepath); } return uri; } private String getOriginalFilepath(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); String originalFilepath = filepath; if (uri.getScheme().equals("content")) { try { Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null); if (cursor.moveToFirst()) { originalFilepath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } } catch (IllegalArgumentException ignored) { } } return originalFilepath; } private InputStream getInputStream(String filepath) throws IORejectionException { Uri uri = getFileUri(filepath); InputStream stream; try { stream = reactContext.getContentResolver().openInputStream(uri); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an input stream for '" + filepath + "'"); } return stream; } private OutputStream getOutputStream(String filepath, boolean append) throws IORejectionException { Uri uri = getFileUri(filepath); OutputStream stream; try { stream = reactContext.getContentResolver().openOutputStream(uri, append ? "wa" : "w"); } catch (FileNotFoundException ex) { throw new IORejectionException("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } if (stream == null) { throw new IORejectionException("ENOENT", "ENOENT: could not open an output stream for '" + filepath + "'"); } return stream; } private static byte[] getInputStreamBytes(InputStream inputStream) throws IOException { byte[] bytesResult; ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; try { int len; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } bytesResult = byteBuffer.toByteArray(); } finally { try { byteBuffer.close(); } catch (IOException ignored) { } } return bytesResult; } @ReactMethod public void writeFile(String filepath, String base64Content, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, false); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void appendFile(String filepath, String base64Content, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void write(String filepath, String base64Content, int position, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); if (position < 0) { OutputStream outputStream = getOutputStream(filepath, true); outputStream.write(bytes); outputStream.close(); } else { RandomAccessFile file = new RandomAccessFile(filepath, "rw"); file.seek(position); file.write(bytes); file.close(); } promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void exists(String filepath, Promise promise) { try { File file = new File(filepath); promise.resolve(file.exists()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFile(String filepath, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] inputData = getInputStreamBytes(inputStream); String base64Content = Base64.encodeToString(inputData, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void read(String filepath, int length, int position, Promise promise) { try { InputStream inputStream = getInputStream(filepath); byte[] buffer = new byte[length]; inputStream.skip(position); int bytesRead = inputStream.read(buffer, 0, length); String base64Content = Base64.encodeToString(buffer, 0, bytesRead, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void readFileAssets(String filepath, Promise promise) { InputStream stream = null; try { // ensure isn't a directory AssetManager assetManager = getReactApplicationContext().getAssets(); stream = assetManager.open(filepath, 0); if (stream == null) { reject(promise, filepath, new Exception("Failed to open file")); return; } byte[] buffer = new byte[stream.available()]; stream.read(buffer); String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } finally { if (stream != null) { try { stream.close(); } catch (IOException ignored) { } } } } @ReactMethod public void hash(String filepath, String algorithm, Promise promise) { try { Map<String, String> algorithms = new HashMap<>(); algorithms.put("md5", "MD5"); algorithms.put("sha1", "SHA-1"); algorithms.put("sha224", "SHA-224"); algorithms.put("sha256", "SHA-256"); algorithms.put("sha384", "SHA-384"); algorithms.put("sha512", "SHA-512"); if (!algorithms.containsKey(algorithm)) throw new Exception("Invalid hash algorithm"); File file = new File(filepath); if (file.isDirectory()) { rejectFileIsDirectory(promise); return; } if (!file.exists()) { rejectFileNotFound(promise, filepath); return; } MessageDigest md = MessageDigest.getInstance(algorithms.get(algorithm)); FileInputStream inputStream = new FileInputStream(filepath); byte[] buffer = new byte[1024 * 10]; // 10 KB Buffer int read; while ((read = inputStream.read(buffer)) != -1) { md.update(buffer, 0, read); } StringBuilder hexString = new StringBuilder(); for (byte digestByte : md.digest()) hexString.append(String.format("%02x", digestByte)); promise.resolve(hexString.toString()); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void moveFile(String filepath, String destPath, Promise promise) { try { File inFile = new File(filepath); if (!inFile.renameTo(new File(destPath))) { copyFile(filepath, destPath); inFile.delete(); } promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void copyFile(String filepath, String destPath, ReadableMap options, Promise promise) { try { copyFile(filepath, destPath); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void copyFile(String filepath, String destPath) throws IOException, IORejectionException { InputStream in = getInputStream(filepath); OutputStream out = getOutputStream(destPath, false); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } @ReactMethod public void readDir(String directory, Promise promise) { try { File file = new File(directory); if (!file.exists()) throw new Exception("Folder does not exist"); File[] files = file.listFiles(); WritableArray fileMaps = Arguments.createArray(); for (File childFile : files) { WritableMap fileMap = Arguments.createMap(); fileMap.putDouble("mtime", (double) childFile.lastModified() / 1000); fileMap.putString("name", childFile.getName()); fileMap.putString("path", childFile.getAbsolutePath()); fileMap.putInt("size", (int) childFile.length()); fileMap.putInt("type", childFile.isDirectory() ? 1 : 0); fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (Exception ex) { ex.printStackTrace(); reject(promise, directory, ex); } } @ReactMethod public void readDirAssets(String directory, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); String[] list = assetManager.list(directory); WritableArray fileMaps = Arguments.createArray(); for (String childFile : list) { WritableMap fileMap = Arguments.createMap(); fileMap.putString("name", childFile); String path = directory.isEmpty() ? childFile : String.format("%s/%s", directory, childFile); // don't allow / at the start when directory is "" fileMap.putString("path", path); int length = 0; boolean isDirectory = true; try { AssetFileDescriptor assetFileDescriptor = assetManager.openFd(path); if (assetFileDescriptor != null) { length = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); isDirectory = false; } } catch (IOException ex) { //.. ah.. is a directory or a compressed file? isDirectory = ex.getMessage().indexOf("compressed") == -1; } fileMap.putInt("size", length); fileMap.putInt("type", isDirectory ? 1 : 0); // if 0, probably a folder.. fileMaps.pushMap(fileMap); } promise.resolve(fileMaps); } catch (IOException e) { reject(promise, directory, e); } } @ReactMethod public void copyFileAssets(String assetPath, String destination, Promise promise) { AssetManager assetManager = getReactApplicationContext().getAssets(); try { InputStream in = assetManager.open(assetPath); copyInputStream(in, assetPath, destination, promise); } catch (IOException e) { // Default error message is just asset name, so make a more helpful error here. reject(promise, assetPath, new Exception(String.format("Asset '%s' could not be opened", assetPath))); } } @ReactMethod public void existsAssets(String filepath, Promise promise) { try { AssetManager assetManager = getReactApplicationContext().getAssets(); try { String[] list = assetManager.list(filepath); if (list != null && list.length > 0) { promise.resolve(true); return; } } catch (Exception ignored) { //.. probably not a directory then } // Attempt to open file (win = exists) InputStream fileStream = null; try { fileStream = assetManager.open(filepath); promise.resolve(true); } catch (Exception ex) { promise.resolve(false); // don't throw an error, resolve false } finally { if (fileStream != null) { try { fileStream.close(); } catch (Exception ignored) { } } } } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } /** * Internal method for copying that works with any InputStream * * @param in InputStream from assets or file * @param source source path (only used for logging errors) * @param destination destination path * @param promise React Callback */ private void copyInputStream(InputStream in, String source, String destination, Promise promise) { OutputStream out = null; try { out = getOutputStream(destination, false); byte[] buffer = new byte[1024 * 10]; // 10k buffer int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } // Success! promise.resolve(null); } catch (Exception ex) { reject(promise, source, new Exception(String.format("Failed to copy '%s' to %s (%s)", source, destination, ex.getLocalizedMessage()))); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } if (out != null) { try { out.close(); } catch (IOException ignored) { } } } } @ReactMethod public void setReadable(String filepath, Boolean readable, Boolean ownerOnly, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); file.setReadable(readable, ownerOnly); promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void stat(String filepath, Promise promise) { try { String originalFilepath = getOriginalFilepath(filepath); File file = new File(originalFilepath); if (!file.exists()) throw new Exception("File does not exist"); WritableMap statMap = Arguments.createMap(); statMap.putInt("ctime", (int) (file.lastModified() / 1000)); statMap.putInt("mtime", (int) (file.lastModified() / 1000)); statMap.putInt("size", (int) file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); statMap.putString("originalFilepath", originalFilepath); promise.resolve(statMap); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void unlink(String filepath, Promise promise) { try { File file = new File(filepath); if (!file.exists()) throw new Exception("File does not exist"); DeleteRecursive(file); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void DeleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { DeleteRecursive(child); } } fileOrDirectory.delete(); } @ReactMethod public void mkdir(String filepath, ReadableMap options, Promise promise) { try { File file = new File(filepath); file.mkdirs(); boolean exists = file.exists(); if (!exists) throw new Exception("Directory could not be created"); promise.resolve(null); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(RCTNativeAppEventEmitter.class) .emit(eventName, params); } @ReactMethod public void downloadFile(final ReadableMap options, final Promise promise) { try { File file = new File(options.getString("toFile")); URL url = new URL(options.getString("fromUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); int progressDivider = options.getInt("progressDivider"); int readTimeout = options.getInt("readTimeout"); int connectionTimeout = options.getInt("connectionTimeout"); DownloadParams params = new DownloadParams(); params.src = url; params.dest = file; params.headers = headers; params.progressDivider = progressDivider; params.readTimeout = readTimeout; params.connectionTimeout = connectionTimeout; params.onTaskCompleted = new DownloadParams.OnTaskCompleted() { public void onTaskCompleted(DownloadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); promise.resolve(infoMap); } else { reject(promise, options.getString("toFile"), res.exception); } } }; params.onDownloadBegin = new DownloadParams.OnDownloadBegin() { public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) { WritableMap headersMap = Arguments.createMap(); for (Map.Entry<String, String> entry : headers.entrySet()) { headersMap.putString(entry.getKey(), entry.getValue()); } WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("statusCode", statusCode); data.putInt("contentLength", contentLength); data.putMap("headers", headersMap); sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data); } }; params.onDownloadProgress = new DownloadParams.OnDownloadProgress() { public void onDownloadProgress(int contentLength, int bytesWritten) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("contentLength", contentLength); data.putInt("bytesWritten", bytesWritten); sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data); } }; Downloader downloader = new Downloader(); downloader.execute(params); this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toFile"), ex); } } @ReactMethod public void stopDownload(int jobId) { Downloader downloader = this.downloaders.get(jobId); if (downloader != null) { downloader.stop(); } } @ReactMethod public void uploadFiles(final ReadableMap options, final Promise promise) { try { ReadableArray files = options.getArray("files"); URL url = new URL(options.getString("toUrl")); final int jobId = options.getInt("jobId"); ReadableMap headers = options.getMap("headers"); ReadableMap fields = options.getMap("fields"); String method = options.getString("method"); ArrayList<ReadableMap> fileList = new ArrayList<>(); UploadParams params = new UploadParams(); for(int i =0;i<files.size();i++){ fileList.add(files.getMap(i)); } params.src = url; params.files =fileList; params.headers = headers; params.method=method; params.fields=fields; params.onUploadComplete = new UploadParams.onUploadComplete() { public void onUploadComplete(UploadResult res) { if (res.exception == null) { WritableMap infoMap = Arguments.createMap(); infoMap.putInt("jobId", jobId); infoMap.putInt("statusCode", res.statusCode); infoMap.putMap("headers",res.headers); infoMap.putString("body",res.body); promise.resolve(infoMap); } else { reject(promise, options.getString("toUrl"), res.exception); } } }; params.onUploadBegin = new UploadParams.onUploadBegin() { public void onUploadBegin() { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); sendEvent(getReactApplicationContext(), "UploadBegin-" + jobId, data); } }; params.onUploadProgress = new UploadParams.onUploadProgress() { public void onUploadProgress(int fileCount,int totalBytesExpectedToSend,int totalBytesSent) { WritableMap data = Arguments.createMap(); data.putInt("jobId", jobId); data.putInt("FileID",fileCount); data.putInt("totalBytesExpectedToSend", totalBytesExpectedToSend); data.putInt("totalBytesSent", totalBytesSent); sendEvent(getReactApplicationContext(), "UploadProgress-" + jobId, data); } }; Uploader uploader = new Uploader(); uploader.execute(params); this.uploaders.put(jobId, uploader); } catch (Exception ex) { ex.printStackTrace(); reject(promise, options.getString("toUrl"), ex); } } @ReactMethod public void stopUpload(int jobId) { Uploader uploader = this.uploaders.get(jobId); if (uploader != null) { uploader.stop(); } } @ReactMethod public void pathForBundle(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void pathForGroup(String bundleNamed, Promise promise) { // TODO: Not sure what equivalent would be? } @ReactMethod public void getFSInfo(Promise promise) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long totalSpace; long freeSpace; if (android.os.Build.VERSION.SDK_INT >= 18) { totalSpace = stat.getTotalBytes(); freeSpace = stat.getFreeBytes(); } else { long blockSize = stat.getBlockSize(); totalSpace = blockSize * stat.getBlockCount(); freeSpace = blockSize * stat.getAvailableBlocks(); } WritableMap info = Arguments.createMap(); info.putDouble("totalSpace", (double) totalSpace); // Int32 too small, must use Double info.putDouble("freeSpace", (double) freeSpace); promise.resolve(info); } @ReactMethod public void touch(String filepath, double mtime, double ctime, Promise promise) { try { File file = new File(filepath); promise.resolve(file.setLastModified((long) mtime)); } catch (Exception ex) { ex.printStackTrace(); reject(promise, filepath, ex); } } @ReactMethod public void getAllExternalFilesDirs(Promise promise){ File[] allExternalFilesDirs = this.getReactApplicationContext().getExternalFilesDirs(null); WritableArray fs = Arguments.createArray(); for (File f : allExternalFilesDirs) { fs.pushString(f.getAbsolutePath()); } promise.resolve(fs); } private void reject(Promise promise, String filepath, Exception ex) { if (ex instanceof FileNotFoundException) { rejectFileNotFound(promise, filepath); return; } if (ex instanceof IORejectionException) { IORejectionException ioRejectionException = (IORejectionException) ex; promise.reject(ioRejectionException.getCode(), ioRejectionException.getMessage()); return; } promise.reject(null, ex.getMessage()); } private void rejectFileNotFound(Promise promise, String filepath) { promise.reject("ENOENT", "ENOENT: no such file or directory, open '" + filepath + "'"); } private void rejectFileIsDirectory(Promise promise) { promise.reject("EISDIR", "EISDIR: illegal operation on a directory, read"); } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put(RNFSDocumentDirectory, 0); constants.put(RNFSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); constants.put(RNFSTemporaryDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(RNFSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); constants.put(RNFSFileTypeRegular, 0); constants.put(RNFSFileTypeDirectory, 1); File externalStorageDirectory = Environment.getExternalStorageDirectory(); if (externalStorageDirectory != null) { constants.put(RNFSExternalStorageDirectoryPath, externalStorageDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalStorageDirectoryPath, null); } File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null); if (externalDirectory != null) { constants.put(RNFSExternalDirectoryPath, externalDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalDirectoryPath, null); } File externalCachesDirectory = this.getReactApplicationContext().getExternalCacheDir(); if (externalCachesDirectory != null) { constants.put(RNFSExternalCachesDirectoryPath, externalCachesDirectory.getAbsolutePath()); } else { constants.put(RNFSExternalCachesDirectoryPath, null); } return constants; } }
package org.hisp.dhis.android.core.arch.helpers; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import org.hisp.dhis.android.core.maintenance.D2Error; import org.hisp.dhis.android.core.maintenance.D2ErrorCode; import org.hisp.dhis.android.core.maintenance.D2ErrorComponent; import java.io.File; import java.io.FileOutputStream; public final class FileResizerHelper { public enum Dimension { SMALL(256), MEDIUM(512), LARGE(1024); private final int dimension; Dimension(int dimension) { this.dimension = dimension; } public int getDimension() { return dimension; } } private FileResizerHelper() {} public static File resizeFile(File fileToResize, Dimension dimension) throws D2Error { Bitmap bitmap = BitmapFactory.decodeFile(fileToResize.getAbsolutePath()); Float width = ((Integer) bitmap.getWidth()).floatValue(); Float height = ((Integer) bitmap.getHeight()).floatValue(); float scaleFactor = width / height; if (scaleFactor > 1) { return resize(fileToResize, bitmap, dimension.getDimension(), (int) (scaleFactor * dimension.getDimension())); } else { return resize(fileToResize, bitmap, (int) (scaleFactor * dimension.getDimension()), dimension.getDimension()); } } private static File resize(File fileToResize, Bitmap bitmap, int dstWidth, int dstHeight) throws D2Error { Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, false); File resizedFile = new File(fileToResize.getParent(), "resized-" + fileToResize.getName()); FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(resizedFile); scaledBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); bitmap.recycle(); scaledBitmap.recycle(); } catch (Exception e) { throw D2Error.builder() .errorComponent(D2ErrorComponent.SDK) .errorCode(D2ErrorCode.FAIL_RESIZING_IMAGE) .errorDescription(e.getMessage()) .build(); } return resizedFile; } }
package il.co.topq.report.plugins.mail; import java.io.StringWriter; import org.apache.commons.lang3.StringUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import il.co.topq.report.Common; import il.co.topq.report.Configuration; import il.co.topq.report.Configuration.ConfigProps; import il.co.topq.report.business.execution.ExecutionMetadata; import il.co.topq.report.plugins.ExecutionPlugin; public class DefaultMailPlugin implements ExecutionPlugin { private final Logger log = LoggerFactory.getLogger(DefaultMailPlugin.class); private static final String DEFAULT_SUBJECT = "Test execution ended"; private MailSender sender; private boolean enabled = true; public DefaultMailPlugin() { enabled = Configuration.INSTANCE.readBoolean(ConfigProps.ENABLE_MAIL); } @Override public String getName() { return "defaultMailPlugin"; } @Override public void onExecutionEnded(ExecutionMetadata metadata) { if (!enabled) { return; } sendMail(metadata); } protected void sendMail(ExecutionMetadata metadata) { configureMailSender(); if (null == sender) { // We already logged an appropriate log message in the // configureMailServer method, so there is no need in adding another // log message here. return; } if (null == metadata) { log.error("Can't find meta data for ended execution. Will not send mail"); return; } final String subject = getMailSubject(metadata); final String body = getMailBody(metadata); new Thread() { public void run() { try { sender.sendMail(subject, body); } catch (Exception e) { log.error("Failed sending mail", e); } } }.start(); } protected String getMailBody(ExecutionMetadata metadata) { return populateTemplate(metadata); } protected String getMailSubject(ExecutionMetadata metadata) { String subject = StringUtils.isEmpty(Configuration.INSTANCE.readString(ConfigProps.MAIL_SUBJECT)) ? DEFAULT_SUBJECT : Configuration.INSTANCE.readString(ConfigProps.MAIL_SUBJECT); if (metadata.getNumOfFailedTests() > 0) { subject += " - Ended with " + metadata.getNumOfFailedTests() + " failures out of " + metadata.getNumOfTests(); } else if (metadata.getNumOfTestsWithWarnings() > 0) { subject += " - Ended with " + metadata.getNumOfTestsWithWarnings() + " warnings out of " + metadata.getNumOfTests(); } else { subject += " - Ended with " + metadata.getNumOfTests() + " successful tests"; } return subject; } private String populateTemplate(ExecutionMetadata metadata) { VelocityEngine ve = new VelocityEngine(); ve.init(); Template t = ve.getTemplate(getTemplateName()); /* create a context and add data */ VelocityContext context = new VelocityContext(); context.put("meta", metadata); final StringWriter writer = new StringWriter(); t.merge(context, writer); return writer.toString(); } protected String getTemplateName() { return Common.CONFIUGRATION_FOLDER_NAME + "/mail.vm"; } protected void configureMailSender() { if (!enabled || null != sender) { return; } sender = new MailSender(); sender.setMailMessageAsHtmlText(true); final String host = Configuration.INSTANCE.readString(ConfigProps.MAIL_SMTP_HOST); if (StringUtils.isEmpty(host)) { log.warn("SMTP host is not configured. Can't send mail"); enabled = false; return; } sender.setSmtpHostName(host); final int port = Configuration.INSTANCE.readInt(ConfigProps.MAIL_SMTP_PORT); if (port == 0) { log.warn("SMTP port is not configured. Can't send mail"); enabled = false; return; } sender.setSmtpPort(port); final String userName = Configuration.INSTANCE.readString(ConfigProps.MAIL_USER_NAME); if (!StringUtils.isEmpty(userName)) { sender.setUserName(userName); } else { log.warn("SMTP User name is not configured."); } final String password = Configuration.INSTANCE.readString(ConfigProps.MAIL_PASSWORD); if (!StringUtils.isEmpty(password)) { sender.setPassword(password); } else { log.warn("SMTP User name is not configured."); } final boolean ssl = Configuration.INSTANCE.readBoolean(ConfigProps.MAIL_SSL); sender.setSsl(ssl); final String from = getFromAddress(); if (StringUtils.isEmpty(from)) { log.warn("Mail from address is not configured. Can't send mail"); enabled = false; return; } sender.setFromAddress(from); final String to = getToAddress(); if (StringUtils.isEmpty(to)) { log.warn("Mail to address is not configured. Can't send mail"); enabled = false; return; } sender.setSendTo(to); final String cc = getCcAddresses(); if (!StringUtils.isEmpty(cc)) { sender.setSendCc(cc.split(",")); } } protected String getCcAddresses() { return Configuration.INSTANCE.readString(ConfigProps.MAIL_CC_ADDRESS); } protected String getToAddress() { return Configuration.INSTANCE.readString(ConfigProps.MAIL_TO_ADDRESS); } protected String getFromAddress() { return Configuration.INSTANCE.readString(ConfigProps.MAIL_FROM_ADDRESS); } }
package com.agileinnovative.blinkstick; import java.util.Hashtable; import java.util.Random; import android.hardware.usb.UsbConstants; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; /** * Class designed to communicate with BlinkStick devices. */ public class BlinkStick { protected static final int STD_USB_REQUEST_GET_DESCRIPTOR = 0x06; protected static final int LIBUSB_DT_STRING = 0x03; /** * USB device object to communicate directly with BlinkStick */ private UsbDevice device = null; /** * USB connection for communicating with BlinkStick */ private UsbDeviceConnection connection; /** * Cached manufacturer name */ private String manufacturer = null; /** * Cached product name */ private String productName = null; /** * Assign UsbDevice * * @param device object to communicate directly with BlinkStick */ public void setDevice(UsbDevice device) { this.device = device; } /** * Get UsbDevice * * @return USB device reference */ public UsbDevice getDevice() { return this.device; } /** * Assign USB device connection * * @param con Connection object to communicate with BlinkStick device */ public void setConnection(UsbDeviceConnection con) { connection = con; } private int _VersionMajor = -1; /** * Get major version number from serial * * @return Major version number as int */ public int getVersionMajor() { if (_VersionMajor == -1) { _VersionMajor = Integer.parseInt(getSerial().substring(getSerial().length() - 3, getSerial().length() - 2)); } return _VersionMajor; } private int _VersionMinor = -1; /** * Get minor version number from serial * * @return Minor version number as int */ public int getVersionMinor() { if (_VersionMinor == -1) { _VersionMinor = Integer.parseInt(getSerial().substring(getSerial().length() - 1, getSerial().length())); } return _VersionMinor; } /** * Check if BlinkStick is connected * * @return Returns true if BlinkStick is connected */ public boolean isConnected() { return connection != null; } /** * Set the color of the device with separate r, g and b int values. * The values are automatically converted to byte values * * @param r red int color value 0..255 * @param g gree int color value 0..255 * @param b blue int color value 0..255 */ public void setColor(int r, int g, int b) { this.setColor((byte) r, (byte) g, (byte) b); } /** * Set the color of the device with separate r, g and b byte values * * @param r red byte color value 0..255 * @param g gree byte color value 0..255 * @param b blue byte color value 0..255 */ public void setColor(byte r, byte g, byte b) { try { sendFeatureReport(new byte[] {1, r, g, b}); } catch (Exception e) { e.printStackTrace(); } } /** * Sends feature report to BlinkStick * * @param buffer An array of bytes to send to the device. First byte has to be report id. */ private void sendFeatureReport(byte[] buffer) { if (connection != null) { connection.controlTransfer(0x20, 0x9, buffer[0], 0, buffer, buffer.length, 2000); } } /** * Get feature report from BlinkStick * * @param buffer An array of bytes to receive from the device. First byte has to be report id. The array must be initialized with correct size. * * @return Number of bytes read from the device */ private int getFeatureReport(byte[] buffer) { if (connection != null) { return connection.controlTransfer(0x80 | 0x20, 0x1, buffer[0], 0, buffer, buffer.length, 2000); } return 0; } /** * Set indexed color of the device with separate r, g and b byte values for channel and LED index * * @param channel Channel (0 - R, 1 - G, 2 - B) * @param index Index of the LED * @param r red int color value 0..255 * @param g gree int color value 0..255 * @param b blue int color value 0..255 */ public void setIndexedColor(int channel, int index, int r, int g, int b) { this.setIndexedColor((byte)channel, (byte)index, (byte)r, (byte)g, (byte)b); } /** * Set indexed color of the device with separate r, g and b byte values for channel and LED index * * @param channel Channel (0 - R, 1 - G, 2 - B) * @param index Index of the LED * @param r red byte color value 0..255 * @param g gree byte color value 0..255 * @param b blue byte color value 0..255 */ public void setIndexedColor(byte channel, byte index, byte r, byte g, byte b) { try { sendFeatureReport(new byte[] {5, channel, index, r, g, b}); } catch (Exception e) { e.printStackTrace(); } } /** * Set the indexed color of BlinkStick Pro with Processing color value * * @param channel Channel (0 - R, 1 - G, 2 - B) * @param index Index of the LED * @param value color as int */ public void setIndexedColor(int channel, int index, int value) { int r = (value >> 16) & 0xFF; int g = (value >> 8) & 0xFF; int b = value & 0xFF; this.setIndexedColor(channel, index, r, g, b); } /** * Set the indexed color of BlinkStick Pro with Processing color value for channel 0 * * @param index Index of the LED * @param value color as int */ public void setIndexedColor(int index, int value) { int r = (value >> 16) & 0xFF; int g = (value >> 8) & 0xFF; int b = value & 0xFF; this.setIndexedColor(0, index, r, g, b); } /** * Set the color of the device with Processing color value * * @param value color as int */ public void setColor(int value) { int r = (value >> 16) & 0xFF; int g = (value >> 8) & 0xFF; int b = value & 0xFF; this.setColor(r, g, b); } /** * Set the color of the device with string value * * @param value this can either be a named color "red", "green", "blue" and etc. * or a hex color in #rrggbb format */ public void setColor(String value) { if (COLORS.containsKey(value)) { this.setColor(hex2Rgb(COLORS.get(value))); } else { this.setColor(hex2Rgb(value)); } } /** * Set random color */ public void setRandomColor() { Random random = new Random(); this.setColor( random.nextInt(256), random.nextInt(256), random.nextInt(256)); } /** * Turn BlinkStick off */ public void turnOff() { this.setColor(0, 0, 0); } /** * Convert hex string to color object * * @param colorStr Color value as hex string #rrggbb * * @return color object */ private int hex2Rgb(String colorStr) { int red = Integer.valueOf(colorStr.substring(1, 3), 16)+ 0; int green = Integer.valueOf(colorStr.substring(3, 5), 16) + 0; int blue = Integer.valueOf(colorStr.substring(5, 7), 16) + 0; return (255 << 24) | (red << 16) | (green << 8) | blue; } /** * Get the current color of the device as int * * @return The current color of the device as int */ public int getColor() { byte[] data = new byte[33]; data[0] = 1;// First byte is ReportID try { int read = getFeatureReport(data); if (read > 0) { return (255 << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; } } catch (Exception e) { } return 0; } /** * Get the current color of the device in #rrggbb format * * @return Returns the current color of the device as #rrggbb formated string */ public String getColorString() { int c = getColor(); int red = (c >> 16) & 0xFF; int green = (c >> 8) & 0xFF; int blue = c & 0xFF; return "#" + String.format("%02X", red) + String.format("%02X", green) + String.format("%02X", blue); } /** * Get value of InfoBlocks * * @param id InfoBlock id, should be 1 or 2 as only supported info blocks */ private String getInfoBlock(int id) { byte[] data = new byte[33]; data[0] = (byte) (id + 1); String result = ""; try { int read = getFeatureReport(data); if (read > 0) { for (int i = 1; i < data.length; i++) { if (i == 0) { break; } result += (char) data[i]; } } } catch (Exception e) { } return result; } /** * Get value of InfoBlock1 * * @return The value of info block 1 */ public String getInfoBlock1() { return getInfoBlock(1); } /** * Get value of InfoBlock2 * * @return The value of info block 2 */ public String getInfoBlock2() { return getInfoBlock(2); } /** * Set value for InfoBlocks * * @param id InfoBlock id, should be 1 or 2 as only supported info blocks * @param value The value to be written to the info block */ private void setInfoBlock(int id, String value) { char[] charArray = value.toCharArray(); byte[] data = new byte[33]; data[0] = (byte) (id + 1); for (int i = 0; i < charArray.length; i++) { if (i > 32) { break; } data[i + 1] = (byte) charArray[i]; } try { sendFeatureReport(data); } catch (Exception e) { e.printStackTrace(); } } /** * Set value for InfoBlock1 * * @param value The value to be written to the info block 1 */ public void setInfoBlock1(String value) { setInfoBlock(1, value); } /** * Set value for InfoBlock2 * * @param value The value to be written to the info block 2 */ public void setInfoBlock2(String value) { setInfoBlock(2, value); } /** * Get the manufacturer of the device * * @return Returns the manufacturer name of the device */ public String getManufacturer() { if (manufacturer == null) { manufacturer = ""; byte[] rawDescs = connection.getRawDescriptors(); byte[] buffer = new byte[255]; int idxMan = rawDescs[14]; try { int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | idxMan, 0, buffer, 0xFF, 0); manufacturer = new String(buffer, 2, rdo - 2, "UTF-16LE"); } catch (Exception e) { } } return manufacturer; } /** * Get the product description of the device * * @return Returns the product name of the device. */ public String getProduct() { if (productName == null) { productName = ""; byte[] rawDescs = connection.getRawDescriptors(); byte[] buffer = new byte[255]; int idxPrd = rawDescs[15]; try { int rdo = connection.controlTransfer(UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_STANDARD, STD_USB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_STRING << 8) | idxPrd, 0, buffer, 0xFF, 0); productName = new String(buffer, 2, rdo - 2, "UTF-16LE"); } catch (Exception e) { } } return productName; } /** * Get the serial number of the device * * @return Returns the serial number of device. */ public String getSerial() { return connection.getSerial(); } /** * Determine report id for the amount of data to be sent * * @return Returns the report id */ private byte determineReportId(int length) { byte reportId = 9; //Automatically determine the correct report id to send the data to if (length <= 8 * 3) { reportId = 6; } else if (length <= 16 * 3) { reportId = 7; } else if (length <= 32 * 3) { reportId = 8; } else if (length <= 64 * 3) { reportId = 9; } else if (length <= 128 * 3) { reportId = 10; } return reportId; } /** * Determine the adjusted maximum amount of LED for the report * * @return Returns the adjusted amount of LED data */ private byte determineMaxLeds(int length) { byte maxLeds = 64; //Automatically determine the correct report id to send the data to if (length <= 8 * 3) { maxLeds = 8; } else if (length <= 16 * 3) { maxLeds = 16; } else if (length <= 32 * 3) { maxLeds = 32; } else if (length <= 64 * 3) { maxLeds = 64; } else if (length <= 128 * 3) { maxLeds = 64; } return maxLeds; } /** * Send a packet of data to LEDs on channel 0 (R) * * @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...] */ public void setColors(byte[] colorData) { this.setColors((byte)0, colorData); } /** * Send a packet of data to LEDs * * @param channel Channel (0 - R, 1 - G, 2 - B) * @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...] */ public void setColors(int channel, byte[] colorData) { this.setColors((byte)channel, colorData); } /** * Send a packet of data to LEDs * * @param channel Channel (0 - R, 1 - G, 2 - B) * @param colorData Report data must be a byte array in the following format: [g0, r0, b0, g1, r1, b1, g2, r2, b2 ...] */ public void setColors(byte channel, byte[] colorData) { byte leds = this.determineMaxLeds(colorData.length); byte[] data = new byte[leds * 3 + 2]; data[0] = this.determineReportId(colorData.length); data[1] = channel; for (int i = 0; i < Math.min(colorData.length, data.length - 2); i++) { data[i + 2] = colorData[i]; } for (int i = colorData.length + 2; i < data.length; i++) { data[i] = 0; } try { sendFeatureReport(data); } catch (Exception e) { e.printStackTrace(); } } /** * Set the mode of BlinkStick Pro as int * * @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror */ public void setMode(int mode) { this.setMode((byte)mode); } /** * Set the mode of BlinkStick Pro as byte * * @param mode 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror */ public void setMode(byte mode) { try { sendFeatureReport(new byte[] {4, mode}); } catch (Exception e) { e.printStackTrace(); } } /** * Get the mode of BlinkStick Pro * * @return 0 - Normal, 1 - Inverse, 2 - WS2812, 3 - WS2812 mirror */ public byte getMode() { byte[] data = new byte[2]; data[0] = 4;// First byte is ReportID try { int read = getFeatureReport(data); if (read > 0) { return data[1]; } } catch (Exception e) { } return -1; } /** * Variable holds the list of valid CSS colors as a hashtable */ private static final Hashtable<String, String> COLORS = new Hashtable<String, String>() { private static final long serialVersionUID = 1L; { put("aqua", "#00ffff"); put("aliceblue", "#f0f8ff"); put("antiquewhite", "#faebd7"); put("black", "#000000"); put("blue", "#0000ff"); put("cyan", "#00ffff"); put("darkblue", "#00008b"); put("darkcyan", "#008b8b"); put("darkgreen", "#006400"); put("darkturquoise", "#00ced1"); put("deepskyblue", "#00bfff"); put("green", "#008000"); put("lime", "#00ff00"); put("mediumblue", "#0000cd"); put("mediumspringgreen", "#00fa9a"); put("navy", "#000080"); put("springgreen", "#00ff7f"); put("teal", "#008080"); put("midnightblue", "#191970"); put("dodgerblue", "#1e90ff"); put("lightseagreen", "#20b2aa"); put("forestgreen", "#228b22"); put("seagreen", "#2e8b57"); put("darkslategray", "#2f4f4f"); put("darkslategrey", "#2f4f4f"); put("limegreen", "#32cd32"); put("mediumseagreen", "#3cb371"); put("turquoise", "#40e0d0"); put("royalblue", "#4169e1"); put("steelblue", "#4682b4"); put("darkslateblue", "#483d8b"); put("mediumturquoise", "#48d1cc"); put("indigo", "#4b0082"); put("darkolivegreen", "#556b2f"); put("cadetblue", "#5f9ea0"); put("cornflowerblue", "#6495ed"); put("mediumaquamarine", "#66cdaa"); put("dimgray", "#696969"); put("dimgrey", "#696969"); put("slateblue", "#6a5acd"); put("olivedrab", "#6b8e23"); put("slategray", "#708090"); put("slategrey", "#708090"); put("lightslategray", "#778899"); put("lightslategrey", "#778899"); put("mediumslateblue", "#7b68ee"); put("lawngreen", "#7cfc00"); put("aquamarine", "#7fffd4"); put("chartreuse", "#7fff00"); put("gray", "#808080"); put("grey", "#808080"); put("maroon", "#800000"); put("olive", "#808000"); put("purple", "#800080"); put("lightskyblue", "#87cefa"); put("skyblue", "#87ceeb"); put("blueviolet", "#8a2be2"); put("darkmagenta", "#8b008b"); put("darkred", "#8b0000"); put("saddlebrown", "#8b4513"); put("darkseagreen", "#8fbc8f"); put("lightgreen", "#90ee90"); put("mediumpurple", "#9370db"); put("darkviolet", "#9400d3"); put("palegreen", "#98fb98"); put("darkorchid", "#9932cc"); put("yellowgreen", "#9acd32"); put("sienna", "#a0522d"); put("brown", "#a52a2a"); put("darkgray", "#a9a9a9"); put("darkgrey", "#a9a9a9"); put("greenyellow", "#adff2f"); put("lightblue", "#add8e6"); put("paleturquoise", "#afeeee"); put("lightsteelblue", "#b0c4de"); put("powderblue", "#b0e0e6"); put("firebrick", "#b22222"); put("darkgoldenrod", "#b8860b"); put("mediumorchid", "#ba55d3"); put("rosybrown", "#bc8f8f"); put("darkkhaki", "#bdb76b"); put("silver", "#c0c0c0"); put("mediumvioletred", "#c71585"); put("indianred", "#cd5c5c"); put("peru", "#cd853f"); put("chocolate", "#d2691e"); put("tan", "#d2b48c"); put("lightgray", "#d3d3d3"); put("lightgrey", "#d3d3d3"); put("thistle", "#d8bfd8"); put("goldenrod", "#daa520"); put("orchid", "#da70d6"); put("palevioletred", "#db7093"); put("crimson", "#dc143c"); put("gainsboro", "#dcdcdc"); put("plum", "#dda0dd"); put("burlywood", "#deb887"); put("lightcyan", "#e0ffff"); put("lavender", "#e6e6fa"); put("darksalmon", "#e9967a"); put("palegoldenrod", "#eee8aa"); put("violet", "#ee82ee"); put("azure", "#f0ffff"); put("honeydew", "#f0fff0"); put("khaki", "#f0e68c"); put("lightcoral", "#f08080"); put("sandybrown", "#f4a460"); put("beige", "#f5f5dc"); put("mintcream", "#f5fffa"); put("wheat", "#f5deb3"); put("whitesmoke", "#f5f5f5"); put("ghostwhite", "#f8f8ff"); put("lightgoldenrodyellow", "#fafad2"); put("linen", "#faf0e6"); put("salmon", "#fa8072"); put("oldlace", "#fdf5e6"); put("bisque", "#ffe4c4"); put("blanchedalmond", "#ffebcd"); put("coral", "#ff7f50"); put("cornsilk", "#fff8dc"); put("darkorange", "#ff8c00"); put("deeppink", "#ff1493"); put("floralwhite", "#fffaf0"); put("fuchsia", "#ff00ff"); put("gold", "#ffd700"); put("hotpink", "#ff69b4"); put("ivory", "#fffff0"); put("lavenderblush", "#fff0f5"); put("lemonchiffon", "#fffacd"); put("lightpink", "#ffb6c1"); put("lightsalmon", "#ffa07a"); put("lightyellow", "#ffffe0"); put("magenta", "#ff00ff"); put("mistyrose", "#ffe4e1"); put("moccasin", "#ffe4b5"); put("navajowhite", "#ffdead"); put("orange", "#ffa500"); put("orangered", "#ff4500"); put("papayawhip", "#ffefd5"); put("peachpuff", "#ffdab9"); put("pink", "#ffc0cb"); put("red", "#ff0000"); put("seashell", "#fff5ee"); put("snow", "#fffafa"); put("tomato", "#ff6347"); put("white", "#ffffff"); put("yellow", "#ffff00"); } }; }